#!/usr/bin/env bash
# Pre-push gate: check attribution, then run the full local CI suite, and BLOCK
# the push if either fails. This is what keeps origin (and the public CI badge)
# green — and keeps the public Contributors list to the people who meant to be
# on it.
#
# Attribution runs FIRST and takes about a second; CI takes minutes. No sense
# burning the CI wait only to reject on a commit trailer at the end of it.
#
# Enable once per clone:   git config core.hooksPath .githooks
# Bypass only for genuine emergencies (e.g. a docs-only push):
#                          git push --no-verify
set -euo pipefail

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

# git hands the pushed refs to this hook on stdin; cache them so we can both
# inspect them here and re-feed them to the attribution guard below.
STDIN_REFS="$(cat)"

# Deletion-only pushes publish no code: every ref line carries an all-zero
# local sha. Running the full CI suite for them is pure waste (a merged-branch
# cleanup costing a full suite run, observed 2026-07-19). Skip both gates —
# nothing is being published, and the attribution guard skips deletes anyway.
if [ -n "$STDIN_REFS" ] && ! printf '%s
' "$STDIN_REFS" | awk '{print $2}' | grep -qv '^0*$'; then
  echo "── pre-push: deletion-only push, nothing published — skipping gates ──"
  exit 0
fi

echo "── pre-push: checking commit attribution ──"
printf '%s
' "$STDIN_REFS" | "$ROOT/scripts/check-commit-attribution.sh"

echo "── pre-push: running local CI gate (mirrors ci.yml) ──"
"$ROOT/scripts/ci-local.sh"
echo "── pre-push: gate green, allowing push ──"
