#!/bin/sh
#
# Run the cheap local gates before a branch is pushed. CI remains the hard gate;
# this hook makes common failures cheap to find in clones that enable it.
#
# Install (once per clone):
#     git config core.hooksPath scripts/hooks
#
# Opt in to the slow gates:
#     AKGL_HOOK_MEMCHECK=1 git push
#     AKGL_HOOK_MUTATION=1 git push
#
# Bypass everything (Git's escape hatch):
#     git push --no-verify

set -eu

ZERO_SHA=0000000000000000000000000000000000000000
has_updates=0
while read -r _local_ref local_sha _remote_ref _remote_sha; do
    if [ "$local_sha" != "$ZERO_SHA" ]; then
        has_updates=1
    fi
done

if [ "$has_updates" -eq 0 ]; then
    exit 0
fi

root=$(git rev-parse --show-toplevel) || exit 1
cd "$root" || exit 1

builddir=${AKGL_HOOK_BUILD_DIR:-$(git rev-parse --git-dir)/akgl-prepush}
mkdir -p "$builddir" || exit 1
logfile="$builddir/last.log"

run() {
    if ! "$@" >"$logfile" 2>&1; then
        echo >&2
        echo "pre-push: FAILED: $*" >&2
        echo "---------------------------------------------------------------" >&2
        cat "$logfile" >&2
        echo "---------------------------------------------------------------" >&2
        echo "pre-push: push aborted. Use 'git push --no-verify' to override." >&2
        exit 1
    fi
}

if [ -x "$root/scripts/cppcheck.sh" ]; then
    echo "pre-push: cppcheck"
    run "$root/scripts/cppcheck.sh"
else
    echo "pre-push: scripts/cppcheck.sh not installed, skipping cppcheck"
fi

echo "pre-push: default build + ctest (excluding performance suites)"
run cmake -S . -B "$builddir/default" -DAKGL_WERROR=ON
run cmake --build "$builddir/default"
run ctest --test-dir "$builddir/default" -LE perf --output-on-failure

if command -v doxygen >/dev/null 2>&1; then
    echo "pre-push: doxygen"
    run doxygen Doxyfile
else
    echo "pre-push: doxygen not installed, skipping documentation check"
fi

if [ "${AKGL_HOOK_MEMCHECK:-0}" = "1" ]; then
    if [ -x "$root/scripts/memcheck.sh" ]; then
        echo "pre-push: memcheck"
        run env AKGL_BUILD_DIR="$builddir/default" "$root/scripts/memcheck.sh"
    else
        echo "pre-push: scripts/memcheck.sh not executable, skipping memcheck"
    fi
fi

if [ "${AKGL_HOOK_MUTATION:-0}" = "1" ]; then
    echo "pre-push: mutation testing (this takes a while)"
    run cmake --build "$builddir/default" --target mutation
fi

echo "pre-push: OK"
exit 0
