#!/usr/bin/env sh
set -eu

status=0
fields=${BLOG_REQUIRED_FIELDS:-title date}
tmp=${TMPDIR:-.}/blog-frontmatter.$$
trap 'rm -f "$tmp"' EXIT HUP INT TERM

if [ "$#" -gt 0 ]; then
  printf '%s\n' "$@" > "$tmp"
else
  : > "$tmp"
  for d in content posts post blog notes garden essays articles src/content src/pages _posts pages; do
    [ -d "$d" ] || continue
    find "$d" -type f \( -name '*.md' -o -name '*.mdx' \) >> "$tmp"
  done
fi

while IFS= read -r f; do
  first=$(sed -n '1p' "$f")
  if [ "$first" != "---" ]; then
    printf 'missing frontmatter: %s\n' "$f"
    status=1
    continue
  fi
  for field in $fields; do
    if ! sed -n '1,/^---$/p' "$f" | rg -q "^$field:"; then
      printf 'missing %s: %s\n' "$field" "$f"
      status=1
    fi
  done
done < "$tmp"

exit "$status"
