#!/bin/sh

# Usage: ./my-org-html file.org

input=$1
case "$input" in *org) ;; *) echo "not org file"; exit 1 ;; esac

org_html_cli="$(dirname $0)/org-html-cli"

# Get "<!-- [[title=...]] ... -->" from input file
# metaline=$(sed -n 's/.*\(<!-- *\[\[.*-->\).*/\1/p;T;q' "$input")
# Need to get metaline on each exporting (so need elisp)

# Elisp config
elisp=$(cat <<EOF

(setq the-input (file-truename "$input"))

;; Use <html lang="ja">
(add-to-list 'org-export-filter-options-functions
             '(lambda (pl _) (plist-put pl :language "ja")))

;; Add <!-- [[..]] .. --> to html file *at second line*
(advice-add 'org-html-template :filter-return
            (lambda (s)
              (let ((lis      (split-string s "\n"))
                    (metaline (get-metaline the-input)))
                (if (not metaline)
                    s
                  (mapconcat (lambda (x) x)
                             (append (list (car lis) metaline) (cdr lis))
                             "\n")))))
(defun get-metaline (file)
  ;; Return "<!-- [[..]] .. -->" from file if found
  (with-temp-buffer
    (insert-file-contents file)
    (goto-char (buffer-end -1))
    (when (search-forward-regexp "<!--\\\\s-*\\\\[\\\\[" nil t)
      (let ((line (buffer-substring (line-beginning-position) (line-end-position))))
        (replace-regexp-in-string ".*\\\\(<!--.*-->\\\\).*" "\\\\1" line)))))

EOF
     )

# Run!
"$org_html_cli" -w -e "$elisp" "$input"

