#!/usr/bin/env bash
# Runs all hook test cases. Each case is a self-contained shell script
# that exits 0 on PASS, non-zero on FAIL.
#
# Cases live in hooks/test/cases/*.sh, are run alphabetically, and
# can use the helper functions/env defined here.

set -u

# Resolve repo root regardless of where this is invoked from.
script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
repo_root=$(cd "$script_dir/../.." && pwd)
HOOK_SCRIPT="$repo_root/hooks/block-git-in-hg.sh"
export HOOK_SCRIPT

if [[ ! -x "$HOOK_SCRIPT" ]]; then
    echo "FATAL: hook script not found or not executable: $HOOK_SCRIPT"
    exit 2
fi

passed=0
failed=0
failed_cases=()

shopt -s nullglob

for case_file in "$script_dir"/cases/*.sh; do
    case_name=$(basename "$case_file" .sh)
    if bash "$case_file" >/tmp/hook_test_out.$$ 2>&1; then
        echo "PASS  $case_name"
        passed=$((passed + 1))
    else
        echo "FAIL  $case_name"
        sed 's/^/      | /' /tmp/hook_test_out.$$
        failed=$((failed + 1))
        failed_cases+=("$case_name")
    fi
    rm -f /tmp/hook_test_out.$$
done

echo
echo "Result: $passed passed, $failed failed"
if (( failed > 0 )); then
    printf '  failed: %s\n' "${failed_cases[@]}"
    exit 1
fi
exit 0
