#!/usr/bin/env bash
# Pre-commit hook: rebuild every CV variant whenever LaTeX sources change.
#
# Activated via:    git config core.hooksPath hooks
# (or run once:     make install-hooks)
#
# Behaviour:
#   - Only fires when staged changes touch .tex sources, the Makefile,
#     or the vendored .cls. Other commits skip the rebuild.
#   - Runs `make all` (i.e. cv-full + cv-short).
#   - Aborts the commit if the build fails.
#   - Copies the rebuilt PDFs to ./pdf/ (tracked) and stages them so each
#     commit ships with up-to-date PDFs alongside the source.

set -euo pipefail

# Skip if no staged file matches a "build input" pattern.
STAGED=$(git diff --cached --name-only --diff-filter=ACMR || true)
if ! echo "$STAGED" | grep -qE '\.(tex|cls)$|^Makefile$'; then
    exit 0
fi

echo "[pre-commit] LaTeX source changed -- rebuilding all CV variants..."

# Build everything. `make all` covers full + short.
if ! make all >/tmp/cv-build.log 2>&1; then
    echo "[pre-commit] BUILD FAILED -- commit aborted." >&2
    echo "[pre-commit] See /tmp/cv-build.log for details." >&2
    tail -30 /tmp/cv-build.log >&2
    exit 1
fi

# Publish the rebuilt PDFs to the tracked ./pdf/ directory and stage them.
mkdir -p pdf
for variant in cv-full cv-short; do
    if [[ -f "build/${variant}.pdf" ]]; then
        cp "build/${variant}.pdf" "pdf/${variant}.pdf"
        git add "pdf/${variant}.pdf"
    fi
done

echo "[pre-commit] Rebuild OK, pdf/ updated and staged."
exit 0
