#!/usr/bin/guile18 -s
!#
(use-modules (ice-9 getopt-long)
	     (alterator common)

	     (alterator algo)
	     (alterator telegraph)
	     (alterator transport pipe-channel)
	     (alterator lookout)
	     (alterator d))

;;; functions

(define *cmdline* (command-line))

(define (usage)
  (format #t "Usage:  ~A [-ld] [module]~%" (car *cmdline*))
  (format #t "  -h, --help     display help screen~%")
  (format #t "  -l,--local     try to use ui files if available~%")
  (format #t "  -d,--debug     turn on debugging~%~%")
  (format #t "  If module name is empty all available modules will be displayed~%")
  (format #t "  Report bugs to http://bugs.altlinux.org/~%")
  (quit))

;;; Generate list containing filenames
(define (files-in-directory dirname)
  (let ((dir (opendir dirname)))
    (let next ((f (readdir dir))
      (files '()))
      (cond ((eof-object? f) (closedir dir) files)
      (else (next (readdir dir) (cons f files)))))))

;; Show all available Alterator modules
(define (list-modules)
  (format #t "Available modules:~%")
  ;;; Display sorted list of module names
  (map
    (lambda (f) (display (format #f "~A~%" (string-drop-right f 8))))
    (sort
      (filter (lambda (f) (equal? (string-suffix-length f ".desktop") 8)) ;; only .desktop file names
        (files-in-directory "/usr/share/alterator/applications"))
      string<))
  (quit))

;; main code

(define option-spec
  '((help  (single-char #\h) (value #f))
    (local (single-char #\l) (value #f))
    (debug (single-char #\d) (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)
    (begin (alterator-init-local)
           (d-init-local))
    (begin (alterator-init-global)
           (d-init-global)))

(define desktop-file (or (cond-car (option-ref options '() #f)) (list-modules)))

(telegraph
  (pipe-in "/usr/bin/alterator-browser-qt")
  (lookout "/standalone" 'desktop-file desktop-file)
  (d))

(telegraph-start)
