#!/usr/bin/env bash
# Pre-push: nothing is pushed unless the whole build succeeds and every ctest
# test passes, as the CI runs them (with the game data tests when the data is
# there). Enabled once per clone with:
#     git config core.hooksPath .githooks
# Build folder: build (or CRUSADER_HOOK_BUILD_DIR), configuration Release.
# The tests run on the working tree, uncommitted changes included.
# Bypass, for an emergency only: git push --no-verify
set -u

root=$(git rev-parse --show-toplevel) || exit 1
build="${CRUSADER_HOOK_BUILD_DIR:-$root/build}"

# Only deleting branches or tags: nothing to test.
pushes=0
while read -r local_ref local_sha remote_ref remote_sha; do
    [ "$local_sha" = "0000000000000000000000000000000000000000" ] || pushes=1
done
[ "$pushes" = 1 ] || exit 0

if [ ! -f "$build/CMakeCache.txt" ]; then
    echo "pre-push: no CMake build in $build (configure it first, or set CRUSADER_HOOK_BUILD_DIR)" >&2
    exit 1
fi

echo "pre-push: building ($build, Release)..."
if ! cmake --build "$build" --config Release; then
    echo "pre-push: the build failed, push refused (a running game locks its exe: close it or rename it)" >&2
    exit 1
fi

echo "pre-push: running every test..."
if ! ctest --test-dir "$build" -C Release --output-on-failure; then
    echo "pre-push: some tests failed, push refused" >&2
    exit 1
fi
echo "pre-push: all tests passed"
