http://www.gnu.org/software/guile/>
General help using GNU software: <http://www.gnu.org/gethelp/>
For complete documentation, run: info '(guile)Using Guile Tools'
" %guile-bug-report-address))

(define (module-commentary mod)
  (file-commentary
   (%search-load-path (module-filename mod))))

(define (module-command-name mod)
  (symbol->string (car (last-pair (module-name mod)))))

(define* (show-usage mod #:optional (port (current-output-port)))
  (let ((usages (string-split
                 (let ((var (module-variable mod '%synopsis)))
                   (if var
                       (variable-ref var)
                       (string-append (module-command-name mod)
                                      " OPTION...")))
                 #\newline)))
    (display "Usage: guild " port)
    (display (car usages))
    (newline port)
    (for-each (lambda (u)
                (display "       guild " port)
                (display u port)
                (newline port))
              (cdr usages))))

(define* (show-summary mod #:optional (port (current-output-port)))
  (let ((var (module-variable mod '%summary)))
    (if var
        (begin
          (display (variable-ref var) port)
          (newline port)))))

(define* (show-help mod #:optional (port (current-output-port)))
  (show-usage mod port)
  (show-summary mod port)
  (cond
   ((module-variable mod '%help)
    => (lambda (var)
         (display (variable-ref var) port)
         (newline port)))
   ((module-commentary mod)
    => (lambda (commentary)
         (newline port)
         (display commentary port)))
   (else
    (format #t "No documentation found for command \"~a\".\n"
            (module-command-name mod)))))

(define %mod (current-module))
(define (main . args)
  (cond
   ((null? args)
    (list-commands #f))
   ((or (equal? args '("--all")) (equal? args '("-a")))
    (list-commands #t))
   ((and (null? (cdr args)) (not (string-prefix? "-" (car args))))
    ;; help for particular command
    (let ((name (car args)))
      (cond
       ((resolve-module `(scripts ,(string->symbol name)) #:ensure #f)
        => (lambda (mod)
             (show-help mod)
             (exit 0)))
       (else
        (format #t "No command named \"~a\".\n" name)
        (exit 1)))))
   (else
    (show-help %mod (current-error-port))
    (exit 1))))
