(use-modules (alterator http template)
             (alterator http html)

             (alterator configd html)
             (alterator configd woo)
             (alterator configd form)
             (alterator configd constraints)
             (alterator configd frontend))

(define (main-args url url-args)
  (let ((args (woo-args url url-args)))
    (or (find (lambda(arg) (string=? url (car arg))) args)
        (car (woo-args url (list  (assoc "language" url-args)))))))

(define *local-help-dir* "html/fbi/help/")
(define *system-help-dir* "/var/www/html/fbi/help/")

(define (help-name url)
  (woo-catch
   (thunk  (cond-assq 'help (woo-template url)))
   (lambda args #f)))

(define (help-variants name)
  (lambda(lang)
    (list
     (and (fluid-ref use-local-files) (string-append *local-help-dir* lang "/" name))
     (string-append *system-help-dir* lang "/" name))))
      
(define (help-path url url-args)
  (or
   (and-let* ((langlist (cond-assoc "language" url-args '("en_US")))
              (name (help-name url)))
             (with-first-readable
              (concatenate
               (map (help-variants name) langlist))
              values))
   "/var/www/html/fbi/help/unknown.html"))

(define (help url url-args)
  (template (help-path url url-args)
            (apply fill-constraints "write" (main-args url url-args))))

(lambda (self objects options)
  (list
   'scm
   (help (string-join (or (cond-cdr objects) '()) "/")
         (cond-plistq 'url-args options))))
