;;; Guix Home Manager.
;;;
;;; Copyright © 2019 Julien Lepiller <julien@lepiller.eu>
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program.  If not, see <http://www.gnu.org/licenses/>.

(define-module (home utils)
  #:use-module (guix build utils)
  #:use-module (guix gexp)
  #:use-module (ice-9 match)
  #:use-module (home)
  #:export (simple-file-home
            symlink-file-home
            make-ini-file))

(define (simple-file-home file-gexp location)
  (user-home
    (home-type
      (name 'simple-file)
      (extensions
        (list
          (home-extension
            (target root-home-type)
            (compute
              (const `((,location ,file-gexp))))))))
    #t))

(define (symlink-file-home to from)
  "Create a symlink from the user home at @var{from} that points to @var{to}."
  (user-home
    (home-type
      (name 'symlink-file)
      (extensions
        (list
          (home-extension
            (target root-home-type)
            (compute
              (const `((,from ,to))))))))
    #t))

(define (make-ini-file name config)
  (define (make-ini-section name config)
    (string-append "[" name "]\n"
                   (string-join
                     (map (lambda (conf)
                            (match conf
                              ((key value)
                               (string-append key "="
                                              (match value
                                                ((? string? val) val)
                                                ((? number? val) (number->string val))
                                                (#t "true")
                                                (#f "false"))))))
                          config)
                     "\n")))
  (plain-file name
    (string-join (map (lambda (section)
                        (match section
                          ((name content)
                           (make-ini-section name content))))
                        config) "\n\n")))