#!/usr/bin/env bash
# Voussoir pre-push guard — refuse a direct push to the protected branch.
#
# `main` lands changes via pull request, gated on the required CI checks
# (lint, tier0-import, test py3.11/3.12/3.13). A local push straight to main
# bypasses that gate. This hook refuses such a push unless the explicit,
# documented escape hatch is set:
#
#     VOUSSOIR_ALLOW_MAIN_PUSH=1 git push origin main
#
# Same posture as `--no-verify`: the hatch is for the rare, documented
# exception (e.g. a docs-only admin fix when CI is wedged) — NOT routine use.
# When you use it, say why in the PR description or commit body. Do not embed
# it in an alias or script.
#
# Installed by scripts/install-git-hooks.sh into .git/hooks/pre-push. The
# protected branch defaults to `main`; override with VOUSSOIR_PROTECTED_BRANCH.
set -euo pipefail

protected="${VOUSSOIR_PROTECTED_BRANCH:-main}"
protected_ref="refs/heads/${protected}"

if [ "${VOUSSOIR_ALLOW_MAIN_PUSH:-0}" = "1" ]; then
    echo "voussoir pre-push: VOUSSOIR_ALLOW_MAIN_PUSH=1 — bypassing ${protected} guard." >&2
    exit 0
fi

# git feeds one line per pushed ref on stdin:
#   <local ref> <local sha> <remote ref> <remote sha>
blocked=0
while read -r _local_ref _local_sha remote_ref _remote_sha; do
    [ -z "${remote_ref:-}" ] && continue
    if [ "$remote_ref" = "$protected_ref" ]; then
        blocked=1
    fi
done

if [ "$blocked" = "1" ]; then
    cat >&2 <<EOF
voussoir pre-push: refusing direct push to '${protected}'.

  '${protected}' is protected — changes land via pull request, gated on the
  required CI checks (lint, tier0-import, test py3.11/3.12/3.13).

  Normal flow:   git push origin <feature-branch>  &&  gh pr create
  Rare exception (documented, non-routine):
                 VOUSSOIR_ALLOW_MAIN_PUSH=1 git push origin ${protected}
EOF
    exit 1
fi

exit 0
