#!/bin/sh
# hureva pre-commit hook shim.
#
# 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). See the `pre-push` shim alongside this
# one for the fuller rationale — this hook follows the same two-stage shape.
#
# Git runs a pre-commit hook with no arguments and nothing useful on stdin; the
# staged tree is read via `git` itself, not this script. Two stages, in order:
#
#   1. A chained pre-existing pre-commit hook (saved next to us as
#      `pre-commit.local` when init detected one). It runs FIRST, and its exit
#      code is passed through UNCHANGED: a customer's own commit gate (e.g. a
#      lint check) must never be masked by hureva. A non-zero exit here blocks
#      the commit.
#
#   2. hureva's own draft -> in_review auto-promotion (`hureva-precommit`).
#      This stage is FAIL-OPEN: any hureva error — a crash, a missing binary —
#      exits 0 and never blocks the commit.

set -u

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-commit.local"
if [ -x "$hureva_chained" ]; then
    "$hureva_chained" "$@"
    hureva_status=$?
    if [ "$hureva_status" -ne 0 ]; then
        # Never masked: the customer's gate said no, so the commit stops here.
        exit "$hureva_status"
    fi
fi

# --- Stage 2: hureva auto-promotion (fail-open — never blocks the commit) -----
if command -v hureva-precommit >/dev/null 2>&1; then
    hureva-precommit "$@" || true
fi

exit 0
