;; Given a .aux file, read the \citation and \bibdata information within it,
;; and interpret a \bibstyle{foo} command as referring to a foo.scm style file.
;; Then parse the .bib file and write out the references as XHTML.
;;
;; This works with beastie v0.9.
;; The functions it uses may change with later versions.
;;
;; This file is part of Beastie <https://purl.org/nxg/dist/beastie>
;; SPDX-FileCopyrightText: 2024 Norman Gray <https://nxg.me.uk>
;; SPDX-License-Identifier: BSD-2-Clause


(module 'aux 'bibtex 'xexpr)

(define (exit/usage)
  (eprintf "Usage:~%    beastie foo.aux~%")
  (exit 1))
(define *aux-file*
  (receive (cmd opts args)
      (getopt '())
    (case (length args)
      ((0) (exit/usage))
      ((1) (car args))
      (else
       (eprintf "Too many arguments.~%")
       (exit/usage)))))

(call-with-aux-file
    *aux-file*
  (λ (citations bibfiles bibstyle)
    (unless bibfiles
      (eprintf "The aux file ~s has no \\bibdata{} command!~%" *aux-file*)
      (exit 1))
    (unless bibstyle
      (eprintf "The aux file ~s has no \\bibstyle{} command!~%" *aux-file*)
      (exit 1))

    ;; load a program which defines ASSEMBLE-BIBLIOGRAPHY
    ;; ((listof symbol?) (listof string?) -> (listof citation?))
    (load bibstyle)

    (let ((refs (assemble-bibliography citations bibfiles)))
      (for-each (λ (citation)
                  (xexpr-write/xml! (citation-html citation))
                  (newline))
                refs))))
