#!/bin/bash
# Test-target compile gate: blocks a push whose test targets do not build.
#
# Activate in a fresh clone (one-time):
#   git config core.hooksPath scripts/githooks
#
# Bypass for a work-in-progress push: git push --no-verify
#
# `cargo check` and `cargo clippy` both compile only the lib and bin targets, so
# a break confined to `tests/` or a `#[cfg(test)]` module is clean under both and
# lands unnoticed (the sqlx 0.9 upgrade shipped exactly that way). `--no-run`
# builds every test target without running them, which is the cheap half of the
# suite and enough to catch a compile break. Tests still run separately.
#
# `--workspace` is load-bearing: default-members is src-tauri alone, so a bare
# `cargo test --no-run` would skip core, db-sqlite, go-mcp, and got.
set -euo pipefail

ROOT="$(git rev-parse --show-toplevel)"
cd "$ROOT"

# Refs arrive on stdin as "<local ref> <local sha> <remote ref> <remote sha>".
# A branch deletion has an all-zero local sha and no tree to build.
pushing=0
while read -r _local_ref local_sha _remote_ref _remote_sha; do
    case "$local_sha" in
        *[!0]*) pushing=1 ;;
    esac
done
[ "$pushing" -eq 1 ] || exit 0

echo "pre-push: building test targets (cargo test --no-run --workspace)..."
if ! cargo test --no-run --workspace; then
    echo "pre-push: test targets failed to build."
    echo "pre-push: push aborted (use --no-verify to bypass)."
    exit 1
fi

echo "pre-push: test targets build clean."
