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

DOC_DIR="doc"
TEX_FILE="main.tex"

script_dir=$(CDPATH= cd "$(dirname "$0")" && pwd)
repo_root=$(CDPATH= cd "$script_dir/.." && pwd)
repo_name="${REPO_NAME:-$(basename "$repo_root")}"
tex_path="$repo_root/$DOC_DIR/$TEX_FILE"

read_tex_command() {
  sed -n "s/^\\\\newcommand{\\\\$1}{\\([^}]*\\)}$/\\1/p" "$tex_path" | head -n 1
}

publisher_domain=$(read_tex_command PublisherDomain)
card_area=$(read_tex_command CardArea)
card_series=$(read_tex_command CardSeries)
card_number=$(read_tex_command CardNumber)
card_slug=$(read_tex_command CardSlug)
card_version=$(read_tex_command CardVersion)
document_uuid=$(read_tex_command DocumentUUID)

if [ -z "$publisher_domain" ] || [ -z "$card_area" ] || [ -z "$card_series" ] || \
  [ -z "$card_number" ] || [ -z "$card_slug" ] || [ -z "$card_version" ] || \
  [ -z "$document_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)
fi
short_commit=$(printf '%s' "$commit" | cut -c1-12)

meta_file="$repo_root/$DOC_DIR/build-meta.tex"
tmp_meta="$meta_file.tmp.$$"
cleanup() {
  rm -f "$meta_file" "$tmp_meta"
}
trap cleanup EXIT HUP INT TERM

printf '\\newcommand{\\BuildCommit}{%s}\n' "$short_commit" > "$tmp_meta"
mv "$tmp_meta" "$meta_file"

pdf_out_dir="${PDF_OUT_DIR:-$repo_root/doc/pdf}"
mkdir -p "$pdf_out_dir"
out_dir=$(CDPATH= cd "$pdf_out_dir" && pwd)
pdf_basename="$publisher_domain-$card_area-$card_series-$card_number-$card_slug-$card_version-$document_uuid.pdf"
find "$out_dir" -maxdepth 1 -type f -name '*.pdf' -delete

(
  cd "$repo_root/$DOC_DIR"
  latexmk -pdf -interaction=nonstopmode -outdir="$out_dir" "$TEX_FILE"
)

source_pdf="$out_dir/${TEX_FILE%.tex}.pdf"
target_pdf="$out_dir/$pdf_basename"
if [ "$source_pdf" != "$target_pdf" ]; then
  mv "$source_pdf" "$target_pdf"
fi

find "$out_dir" -maxdepth 1 -type f \( \
  -name '*.aux' -o \
  -name '*.log' -o \
  -name '*.out' -o \
  -name '*.fls' -o \
  -name '*.fdb_latexmk' \
\) -delete
