#!/bin/sh

set -eu

repo_root=$(git rev-parse --show-toplevel)

echo "pre-push: running make format"
make -C "$repo_root" format

if ! git -C "$repo_root" diff --quiet -- src; then
  echo "pre-push: formatting changed tracked files under src/." >&2
  echo "pre-push: review the changes, stage them, and create a new commit before pushing." >&2
  git -C "$repo_root" --no-pager diff --stat -- src >&2
  exit 1
fi

echo "pre-push: formatting check passed"

if [ "${PRE_PUSH_DOCS_CHECKS:-0}" = "1" ]; then
  if command -v lualatex >/dev/null 2>&1; then
    echo "pre-push: building LaTeX paper"
    (cd "$repo_root/docs/paper" && make jlt-check)
    echo "pre-push: paper build passed"
  else
    echo "pre-push: skipping LaTeX paper build (lualatex not available)"
  fi

  if command -v doxygen >/dev/null 2>&1 && command -v cmake >/dev/null 2>&1; then
    echo "pre-push: building doxygen docs"
    make -C "$repo_root" doxygen
    echo "pre-push: doxygen build passed"
  else
    echo "pre-push: skipping doxygen build (doxygen/cmake not available)"
  fi
else
  echo "pre-push: skipping docs builds (set PRE_PUSH_DOCS_CHECKS=1 to enable)"
fi
