
;; Copyright (C) 2018 Tommi Höynälänmaa
;; Distributed under GNU Lesser General Public License version 3,
;; see file doc/LGPL-3.

(library (theme-d common theme-d-config)

  (export get-theme-d-config-filename
	  load-theme-d-config-file
	  get-theme-d-config-var
	  init-theme-d-config
	  gl-l-config)

  (import (guile)
	  (rnrs exceptions)
	  (rnrs base)
	  (th-scheme-utilities stdutils))

  (define (get-theme-d-config-filename)
    (let ((gl-config-file0 (getenv "THEME_D_CONFIG_FILE")))
      (if (not (eqv? gl-config-file0 #f))
	  gl-config-file0
	  (let* ((str-home (getenv "HOME"))
		 (str-name (string-append str-home "/.theme-d-config")))
	    (if (file-exists? str-name)
		str-name
		"/etc/theme-d-config")))))

  (define (load-theme-d-config-file)
    (let* ((str-filename (get-theme-d-config-filename))
	   (fl (open-input-file str-filename))
	   (x-config (read fl)))
      (close-input-port fl)
      (if (and (list? x-config)
	       (not-null? x-config)
	       (eq? (car x-config) 'theme-d))
	  x-config
	  (raise 'erroneous-theme-d-config-file))))

  (define gl-l-config #f)

  (define (init-theme-d-config)
    (if (eq? gl-l-config #f)
	(set! gl-l-config (load-theme-d-config-file))))
  
  (define (get-theme-d-config-var s-var-name)
    (assert (symbol? s-var-name))
    (assert (and (list? gl-l-config)
  		 (not-null? gl-l-config)
  		 (eq? (car gl-l-config) 'theme-d)))
    (let ((p-assoc (assq s-var-name (cdr gl-l-config))))
      (if p-assoc
  	  ;; The configuration variables are stored as lists of two arguments.
  	  (cadr p-assoc)
  	  ;; We should probably make a condition type for this.
  	  (raise (list 'undefined-theme-d-config-var
  		       (cons 's-var-name s-var-name)))))))
