#!/bin/bash

: "${1:?Missing filename!}"
[ ! -f "$1" ] && { echo "Wrong filename!" >&2; exit 1; }

FILENAME="$(mktemp)"

cleanup() {
    rm -f "$FILENAME"
}

trap 'cleanup' INT HUP TRAP

shift_header() {
    local counter=1
    while read -r line; do
        (( counter+=1 ))
        if [[ "$line" = "# "* ]]; then
            echo "---"
            echo "title: ${line#"# "}"
            echo "---"
            tail -n +"$counter" < "$1"
            return
        fi
    done < "$1"
    cat "$1"
}

main() {
    local -a pandoc_options=(
	'--from=gfm+tex_math_dollars+footnotes+emoji-autolink_bare_uris'
	'--to=html+raw_html'
	'--mathjax'
	"--template=${HOME}/.local/share/default.html"
	"--variable=published_time=$(date -Iseconds -d"$(stat "$1" | grep 'Birth:' | sed 's/.*Birth:\s//')")"
    )
    pandoc "${pandoc_options[@]}" <(shift_header "$1") > "$FILENAME" &&
    echo "$FILENAME" &&
    firefox "$FILENAME" & disown

    sleep 5
    cleanup
}

main "$@"
