#!/usr/bin/guile18 -s
!#
(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))

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

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