#!/bin/sh
# hureva pre-push hook shim.
# Written by hureva @HUREVA_VERSION@ — re-run `hureva init` after upgrading.
#
# Installed by `hureva init` into a repo's tracked `.hureva/hooks/` directory and
# enabled with `git config core.hooksPath .hureva/hooks` (detect-and-chain — if a
# foreign hooks dir is already configured, init installs this shim there instead
# and leaves core.hooksPath untouched).
#
# Git runs a pre-push hook with `<remote-name> <remote-url>` on argv and one
# `<local ref> <local sha> <remote ref> <remote sha>` line per pushed ref on
# stdin. This shim has two stages, in order:
#
#   1. A chained pre-existing pre-push hook (saved next to us as `pre-push.local`
#      when init detected one). It runs FIRST, and its exit code is passed
#      through UNCHANGED: a customer's own push gate (e.g. a test run) must never
#      be masked by hureva. A non-zero exit here blocks the push.
#
#   2. hureva's own transition detection (`hureva prepush`). This stage is
#      FAIL-OPEN (R3): any hureva error — a crash, a missing binary, a dropped
#      network — exits 0 and never blocks the push.
#
# stdin is captured once and replayed to each stage, since git streams the push
# refs there and both stages need them.

set -u

# Capture git's push-ref tuples once so both stages see the same input.
hureva_stdin=$(cat)

hureva_hook_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)

# --- Stage 1: chained pre-existing hook (exit code passed through unchanged) ---
hureva_chained="$hureva_hook_dir/pre-push.local"
if [ -x "$hureva_chained" ]; then
    printf '%s\n' "$hureva_stdin" | "$hureva_chained" "$@"
    hureva_status=$?
    if [ "$hureva_status" -ne 0 ]; then
        # Never masked: the customer's gate said no, so the push stops here.
        exit "$hureva_status"
    fi
fi

# --- Stage 2: hureva detection (fail-open — never blocks the push) ------------
# The guard tests `hureva` alone: `command -v` resolves a single word, so
# guarding on "hureva prepush" would never resolve and would silently disable
# this stage.
if command -v hureva >/dev/null 2>&1; then
    printf '%s\n' "$hureva_stdin" | hureva prepush "$@" || true
else
    # Fail-open still: this never blocks the push. But silence here means specs
    # stop being routed for review with nothing to notice, so say it once.
    echo "hureva: not found on PATH — spec transitions are not being detected." >&2
    echo "  Install it (uv tool install hureva), then run: hureva init" >&2
fi

exit 0
