#!/usr/bin/guile --no-auto-compile
!#
(use-modules (ice-9 getopt-long)
             (vhttpd)
             (alterator common)
             (alterator exit-handler)

             (alterator algo)
             (alterator pipe)
             (alterator woo)
             (alterator d)
             (alterator ensign))

;;; functions

(define (prepare-log logfile)
  (redirect-port (open-output-file logfile) (current-error-port))
  (chmod logfile #o600))

(define *cmdline* (command-line))


(define (usage)
  (format #t "Usage: ~A [-l] [-f] [-t <sec>]~%" program-name)
  (format #t "\t\t-h,--help   this screen ~%")
  (format #t "\t\t-l,--local   try to use local backends if available ~%")
  (format #t "\t\t-d,--debug   turn on debugging ~%")
  (format #t "\tReport bugs to <inger@altlinux.org>~%")
  (quit))

(define (d-message cmd debug)
  (with-ignored-sigpipe
   (lambda()
     (if debug
         (ensign-query cmd)
         (catch #t
                (lambda() (ensign-query cmd))
                pack-exception)))))

;;; main code

(define option-spec
  '((help  (single-char #\h) (value #f))
    (local (single-char #\l) (value #f))
    (debug (single-char #\d) (value #f))
    (foreground (single-char #\f) (value #f))))

(define options (getopt-long *cmdline* option-spec))

(and (option-ref options 'help #f) (usage))
(and (option-ref options 'debug #f) (turn-on-debugging))

(define *d-user* (passwd:name (getpwuid (getuid))))

; /run/alteratord is also used in installer
; to bounce the socket between stage3 and stage2;
; it's also more secure than predefined /tmp subdir
; NB: a copy contained in ../interfaces/guile/d.scm
(define *tmpdir*
  (if (string=? *d-user* "root")
    "/run/alteratord"
    (string-append
      (or (getenv "TMPDIR") "/tmp")
      "/alterator")))

(if (option-ref options 'local #f)
    (alterator-init-local)
    (begin (alterator-init-global)
           (prepare-log (string-append *tmpdir* "/alteratord.log"))))

;; Do not delay logging:
(setvbuf (current-error-port) 'line) ; goes to our custom log
(setvbuf (current-output-port) 'line) ; captured by system log if it's a service
(force-output)

(ensign-init)

(with-exit-handler
  (lambda()
    (d-loop (lambda(cmd) (d-message cmd (option-ref options 'debug #f))))))
