#!/bin/bash
# transform obsidian markdown files to html
#
# example usage: `./transform.sh "/path/to/obsidian/vault/Interesting topic.md"`
# will generate "interesting-topic.html" in the current directory

set -euo pipefail

if [[ $# -ne 1 ]]; then
    echo >&2 "usage: $0 MD_FILE"
    exit 1
elif [[ ! -f "$1" ]]; then
    echo >&2 "error: file '$1' does not exist"
    exit 2
elif [[ ! "$1" =~ \.md$ ]]; then
    echo >&2 "error: need a .md file, but got: '$1'"
    exit 3
fi

in_file=$1
base_name="$(basename "${in_file}" .md)"
out_file_base_name="$(echo "${base_name}" | tr "[:upper:]" "[:lower:]" | sed -e 's/ /-/g')"
out_file="${out_file_base_name}.html"

# the `sed` command strips obsidian's internal link markers, e.g. "More in the [[Other document]]." -> "More in the Other document."
# in contrast to the default pandoc MD format, `commonmark` doesn't need empty lines around headings etc., which obsidian doesn't add on its own
pandoc --standalone --from commonmark <(sed -E 's/\[\[([^\]+)\]\]/\1/g' "${in_file}") --template=./html-template.pandoc --metadata "title=${base_name}" --to html > "${out_file}"
