#!/bin/sh
srcdir="$(dirname $0)"

die() {
  printf '%s\n' "$1" >&2
  exit "${2:-1}"
}

gettitle() {
  sed -n '1s/^#* *//p' "$1"
}

listposts() {
  find "${srcdir}/posts" -type f -regextype posix-extended \
                         -regex '.*/[0-9]{8}-.*\.md' -printf '%f\n' |
  sort -r |
  while read -r file; do
    filedate="$(date -d "${file%%-*}" +%F)"
    printf '+ [%s] [%s](%s)\n' \
      "$filedate" \
      "$(gettitle "${srcdir}/posts/${file}")" \
      "/posts/${file%md}html"
  done
}

preprocess() {
  while IFS= read -r line; do
    case "$line" in
      '@POSTS@') listposts ;;
              *) printf '%s\n' "$line" ;;
    esac
  done < "$1"
}

input="$1"
echo "$input" | grep -sq '\.md$' || die "Usage: $0 INPUT_FILE.md"

cat <<-EOF
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<link rel="stylesheet" type="text/css" href="/css/style.css"/>
	<title>~jlucas/$(gettitle "$input")</title>
</head>
<body>
	<header>
		$(cat "${srcdir}/templates/header.html")
	</header>
<main>
	$(preprocess "$input" | cmark-gfm --unsafe -e strikethrough -e table -e footnotes)
</main>
<footer>
	$(cat "${srcdir}/templates/footer.html")
</footer>
</body>
EOF
