#!/usr/bin/env sh
set -eu
script_dir=$(CDPATH= cd "$(dirname "$0")" && pwd); repo_root=$(CDPATH= cd "$script_dir/.." && pwd); tex_path="$repo_root/doc/main.tex"
read_tex_command() { sed -n "s/^\\\\newcommand{\\\\$1}{\\([^}]*\\)}$/\\1/p" "$tex_path" | head -n 1; }
publisher=$(read_tex_command PublisherDomain); area=$(read_tex_command CardArea); series=$(read_tex_command CardSeries); number=$(read_tex_command CardNumber); slug=$(read_tex_command CardSlug); version=$(read_tex_command CardVersion); uuid=$(read_tex_command DocumentUUID)
if [ -z "$publisher" ] || [ -z "$area" ] || [ -z "$series" ] || [ -z "$number" ] || [ -z "$slug" ] || [ -z "$version" ] || [ -z "$uuid" ]; then echo "missing card metadata in $tex_path" >&2; exit 1; fi
commit=${GITEA_SHA:-${GITHUB_SHA:-}}; if [ -z "$commit" ]; then commit=$(git -C "$repo_root" rev-parse HEAD 2>/dev/null || printf '%s' uncommitted); fi
meta="$repo_root/doc/build-meta.tex"; trap 'rm -f "$meta"' EXIT HUP INT TERM; printf '\\newcommand{\\BuildCommit}{%s}\n' "$(printf '%s' "$commit" | cut -c1-12)" > "$meta"
out="$repo_root/doc/pdf"; mkdir -p "$out"; ( cd "$repo_root/doc" && latexmk -pdf -interaction=nonstopmode -halt-on-error -outdir="$out" main.tex )
target="$out/$publisher-$area-$series-$number-$slug-$version-$uuid.pdf"; mv "$out/main.pdf" "$target"
find "$out" -maxdepth 1 -type f \( -name '*.aux' -o -name '*.log' -o -name '*.out' -o -name '*.fls' -o -name '*.fdb_latexmk' \) -delete
printf '%s\n' "$target"
