#!/usr/bin/guile18 -s
!#
(use-modules (ice-9 getopt-long)
	     (srfi srfi-13)
	     (alterator exit-handler)
	     (alterator common)
	     (alterator algo)
	     (alterator plist)
	     (alterator woo)
	     (alterator d))

;;; functions

(define *cmdline* (command-line))

(define (usage)
  (format #t "Usage:  ~A [-l] script ~%" program-name)
  (format #t "  -h, --help     display help screen~%")
  (format #t "  -l,--local     try to use local files (ui,templates,backend* etc.) if available ~%~%")
  (format #t "  Report bugs to <inger@altlinux.ru>~%")
  (quit))

(define (ai-error . fmt)
  (format (current-error-port) "~A: ~A~%" program-name (apply format #f fmt))
  (exit 1))

(define (type-error-string reasonlist)
  (string-concatenate
    (map (lambda(x) (format #f "~A: ~A~%" (car x) (cdr x)))
	 reasonlist)))

(define (catch/message proc)
  (catch
    'type-error
    (lambda()
      (catch 'woo-error
	     proc
	     (lambda(key reason)
	       (ai-error reason))))
    (lambda(key reasonlist)
      (ai-error (format #f "wrong parameter types~%~A" (type-error-string reasonlist))))))

(define (ai-query cmd)
  (catch/message
    (lambda()
	(format #t "~S~%" cmd)
	(let ((result (d-query cmd)))
	  (cond
	    ((eof-object? result)
	     (ai-error "unexpected eof from alteratord"))
	    ((pair? result)
	     (format #t "\tanswer:~S~%" result))
	    ((not (null? result))
	     (ai-error "wrong answer from alteratord " result)))))))

;;; main code

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

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

(and (option-ref options 'help #f) (usage))

(if (option-ref options 'local #f)
    (begin (alterator-init-local)
           (d-init-local))
    (begin (alterator-init-global)
           (d-init-global)))

(define *script* (or (cond-car (option-ref options '() #f)) (usage)))

(with-exit-handler
  (lambda()
    (call-with-input-file
      *script*
      (lambda(port)
	(let loop ((cmd (read port)))
	  (or (eof-object? cmd)
	      (begin (ai-query cmd)
		     (loop (read port)))))))))
