#!/bin/bash
# Build the combined ECT* 2025 proceedings, ectWS_report_FBsys_combined.pdf.
#
# Usage:  ./build.sh            build
#         ./build.sh clean      remove build artifacts (not the PDF)
#         ./build.sh distclean  remove build artifacts and the PDF
#
# Requires: pdflatex, bibtex (TeX Live 2023 or newer), python3, and ghostscript
# (pulled in by epstopdf, which converts Capitani's two EPS figures).

set -euo pipefail
cd "$(cd "$(dirname "$0")" && pwd)"

DOC=ectWS_report_FBsys_combined
ARTEFACTS=(.aux .bbl .blg .fls .log .out .toc .synctex.gz)

clean() {
  for e in "${ARTEFACTS[@]}"; do rm -f "$DOC$e"; done
  rm -f combined_refs.bib
  rm -f capitani/*-eps-converted-to.pdf
  rm -rf __pycache__
}

case "${1:-build}" in
  clean)     clean; echo "cleaned build artifacts"; exit 0 ;;
  distclean) clean; rm -f "$DOC.pdf"; echo "cleaned build artifacts and PDF"; exit 0 ;;
  build)     ;;
  *) echo "usage: $0 [build|clean|distclean]" >&2; exit 2 ;;
esac

# --- prerequisites -----------------------------------------------------------
missing=0
for prog in pdflatex bibtex python3; do
  command -v "$prog" >/dev/null || { echo "ERROR: '$prog' not found in PATH" >&2; missing=1; }
done
[ "$missing" -eq 0 ] || {
  echo "" >&2
  echo "Install a full TeX Live (e.g. 'texlive-full' on Debian/Ubuntu," >&2
  echo "'texlive-scheme-full' on Fedora, or MacTeX) plus python3." >&2
  exit 1
}

# --- 1. regenerate the merged bibliography -----------------------------------
# The 14 per-contribution .bib files define 565 keys more than once.  Handing
# them to bibtex directly yields 135 "Repeated entry" errors, so they are folded
# into combined_refs.bib first, keeping the first definition of each key --
# exactly what bibtex itself would do.  combined_refs.bib is generated: edit the
# per-contribution .bib files, never it.
echo "==> [1/5] merging bibliographies"
python3 merge_bibs.py

# --- 2-5. pdflatex / bibtex / pdflatex x2 ------------------------------------
# --shell-escape is required: epstopdf converts capitani/*.eps on the fly.
# Three pdflatex passes settle the TOC, the cross-references and the citations.
LATEX="pdflatex -synctex=1 -interaction=nonstopmode -file-line-error --shell-escape"

# '|| true' throughout: in nonstopmode pdflatex exits 1 on any LaTeX error but
# still writes a log.  Letting 'set -e' abort here would skip the report below
# and leave the user with no idea what went wrong; the log is checked instead.
echo "==> [2/5] pdflatex (pass 1)"; $LATEX "$DOC" > /dev/null || true
echo "==> [3/5] bibtex";           bibtex "$DOC"  > /dev/null || true
echo "==> [4/5] pdflatex (pass 2)"; $LATEX "$DOC" > /dev/null || true
echo "==> [5/5] pdflatex (pass 3)"; $LATEX "$DOC" > /dev/null || true

# --- report ------------------------------------------------------------------
echo ""
# -file-line-error reformats errors as "./file.tex:266: Undefined control
# sequence.", so they no longer start with "!".  Match both shapes, or a broken
# build reports zero errors.
ERRPAT='^(!|[^ :]+:[0-9]+: )'
err=$(grep -caE "$ERRPAT" "$DOC.log" || true)
undef_cite=$(grep -Fa 'Citation' "$DOC.log" | grep -ci undefined || true)
undef_ref=$(grep -Fa 'Reference' "$DOC.log" | grep -ci undefined || true)
bibmsg=$(grep -cEa '^Warning|error message' "$DOC.blg" || true)
rerun=$(grep -ca 'Rerun to get' "$DOC.log" || true)

echo "LaTeX errors ......... $err"
echo "bibtex messages ...... $bibmsg"
echo "undefined citations .. $undef_cite"
echo "undefined references . $undef_ref"
echo "rerun requested ...... $rerun"
echo ""

if [ "$err" -ne 0 ]; then
  echo "Build FAILED -- first errors:" >&2
  grep -aE "$ERRPAT" "$DOC.log" | head -10 >&2
  exit 1
fi

grep -a 'Output written' "$DOC.log" || true
echo "Done: $PWD/$DOC.pdf"
