#!/usr/bin/env bash
# tools/hooks/pre-push — the pre-ship blocker (Engineering Directive §1.4/§9.5 #6).
#
# Runs the composed pre-ship gate (charter-floor + security, see
# tools/preship_gate.sh) before any push to staging or main. dev and feature
# branches pass straight through.
#
# Install via: bash tools/install_hooks.sh
# Override for a documented exception: git push --no-verify  (write down WHY).
set -uo pipefail
REPO_ROOT="$(git rev-parse --show-toplevel)"

# git feeds pre-push one line per ref: <local ref> <local oid> <remote ref> <remote oid>
protected=0
while read -r _localref _localoid remoteref _remoteoid; do
  case "$remoteref" in
    refs/heads/staging|refs/heads/main) protected=1 ;;
  esac
done

# Nothing aimed at a protected branch — let the push through.
[ "$protected" -eq 0 ] && exit 0

echo "pre-push: target includes staging/main — running pre-ship gate…"
if bash "$REPO_ROOT/tools/preship_gate.sh"; then
  exit 0
fi
echo "pre-push: BLOCKED by a RED pre-ship gate. Make it GREEN, or 'git push --no-verify' with a written reason." >&2
exit 1
