#!/usr/bin/env bash
# Phoebus pre-commit hook.
#
#   1. refuse large/binary image files;
#   2. scan staged content for secrets;
#   3. run the fast Bash test suite (set PHOEBUS_PRECOMMIT_TESTS=0 to skip);
#   4. optionally run the Rust suite (set PHOEBUS_PRECOMMIT_RUST=1 to enable).
#
# Bypass with: git commit --no-verify   or   SKIP_PHOEBUS_HOOKS=1 git commit ...

set -uo pipefail

[[ "${SKIP_PHOEBUS_HOOKS:-0}" == "1" ]] && exit 0

root="$(git rev-parse --show-toplevel 2>/dev/null)" || exit 0
cd "$root" || exit 0

mapfile -t staged < <(git diff --cached --name-only --diff-filter=ACM)

for file in "${staged[@]}"; do
    [[ -n "$file" ]] || continue
    case "$file" in
        *.iso|*.qcow2|*.img|*.raw)
            printf 'pre-commit: refusing to commit image file %s\n' "$file" >&2
            exit 1
            ;;
    esac
    if [[ -f "$file" ]]; then
        size="$(wc -c <"$file" 2>/dev/null || echo 0)"
        if (( size > 5242880 )); then
            printf 'pre-commit: %s is %s bytes (>5 MiB); refusing\n' "$file" "$size" >&2
            exit 1
        fi
    fi
done

if [[ -x scripts/check-secrets.sh ]]; then
    scripts/check-secrets.sh "${staged[@]}" || exit 1
fi

if [[ "${PHOEBUS_PRECOMMIT_TESTS:-1}" == "1" && -x installer/tests/run_tests.sh ]]; then
    log="/tmp/phoebus-precommit-tests.log"
    if ! bash installer/tests/run_tests.sh >"$log" 2>&1; then
        printf 'pre-commit: tests failed; see %s\n' "$log" >&2
        exit 1
    fi
fi

if [[ "${PHOEBUS_PRECOMMIT_RUST:-0}" == "1" ]] && command -v cargo >/dev/null 2>&1; then
    log="/tmp/phoebus-precommit-rust.log"
    if ! (cd installer-rs && cargo test --workspace) >"$log" 2>&1; then
        printf 'pre-commit: cargo tests failed; see %s\n' "$log" >&2
        exit 1
    fi
fi

exit 0
