#!/usr/bin/env bash
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Works both:
# - in-repo:   finish_ready/scripts/compile_global.sh
# - extracted: scripts/compile_global.sh
if [[ -d "$HERE/../paper" && -d "$HERE/../engine" ]]; then
  ROOT="$(cd "$HERE/.." && pwd)"
elif [[ -d "$HERE/../paper" && -d "$HERE/../../engine" ]]; then
  ROOT="$(cd "$HERE/../.." && pwd)"
else
  echo "Could not locate repository root (engine/ not found)." 1>&2
  exit 2
fi

OUT="$HERE/build_global"
SRC="$ROOT/global_universality"
mkdir -p "$OUT"

# Copy only the sources needed for compilation.
cp "$SRC/"*.tex "$OUT/"

cd "$OUT"
if ! command -v pdflatex >/dev/null 2>&1; then
  echo "pdflatex not found; compile locally in $OUT"
  exit 0
fi
pdflatex -interaction=nonstopmode -halt-on-error -file-line-error GLOBAL_SYNCRE_UNIVERSALITY_THEOREM.tex
pdflatex -interaction=nonstopmode -halt-on-error -file-line-error GLOBAL_SYNCRE_UNIVERSALITY_THEOREM.tex
echo "Built in $OUT"
