#!/bin/sh
#
# ,markdown-to-html - convert markdown to html once
# use ,markdown-preview for continued updates

set -e

# shellcheck disable=SC2312
filename="$(mktemp "${TMPDIR:-/tmp}"/"$(xxd -l2 -ps /dev/urandom)".html)"
outfile=${2:-${filename}}
cat "${XDG_DATA_HOME-}"/pandoc/templates/pandoc-github-template.html >"${outfile}"
pandoc --no-highlight \
  --template "${XDG_DATA_HOME-}"/pandoc/templates/pandoc-github-template.html \
  --output - -f gfm -t html5 \
  --metadata title="$(basename "$1")" "$1" \
  | sed -z 's|<pre class="mermaid"><code>\([^<]*\)</code></pre>|<div class="mermaid">\1</div>|g' >"${outfile}"
# we can safely use `<` in sed as pandoc will convert < in code to &le

[ -z "${NO_OPEN}" ] && open "${outfile}"
