#!/usr/bin/guile -s
!#

(define datadir "../common/")
(load (string-append datadir "command.scm"))
(load (string-append datadir "command-compat.scm"))
(load (string-append datadir "command-pattern.scm"))
(load (string-append datadir "admiral-sandbox.scm"))
(load (string-append datadir "admiral-common.scm"))

(define (valid-expr? expr)
  (and (pair? expr)
       (command? (car expr))
       (let valid-actions? ((lst (cdr expr)))
	 (cond
	   ((null? lst) #t)
	   ((and (pair? (car lst)) (command? (caar lst)))
	    (valid-actions? (cdr lst)))
	   (else #f)))))

(define (read-radm filename)
(read-script filename valid-expr?))


(define (optimize-single-action action)
  (let ((first (car action))
	(second (cdr action)))
    (cons (make-command-pattern first) second)))

;precompile regexps for the actions
(define (optimize-actions lst)
  (let loop ((lst lst)
	     (result '()))
    (if (null? lst)
      result
      (loop (cdr lst) (append result (list (optimize-single-action (car lst))))))))

;find and eval single backward command
;(define (find-and-eval-single-backward match-result cmd lst) #t)

;loop for finding and converting backward hoo commands
(define (find-and-eval-backward match-result cmd actions)
  (format #t "working with reverse command ~A~%" cmd)
  (format #t "working with actions ~A~%" actions))
;  (find-and-eval-single-backward match-result cmd actions)
;  (find-and-eval-backward match-result (read-command) actions))

;find and eval forward woo command
(define (find-and-eval-forward cmd lst)
  (find-and-eval cmd lst
		 (lambda (curr cmd)
		   (command-pattern-match? (make-command-pattern curr) cmd))
		 (lambda (match-result cmd lst)
		   (find-and-eval-backward
		     match-result
		     (read-command)
		     (optimize-actions lst)))))

;write initial information for chooser
(define (opt-init filename) (print-init (read-radm filename)))

;unconvert command using rcommander script
(define (opt-unconvert filename)
  (find-and-eval-forward (read-command) (read-radm filename)))

(opt-init "local_users.radm")
