#!/usr/bin/env bash
#
# pre-push PII guard — block pushing commits whose MESSAGE, author, or
# committer identity leaks a maintainer identifier or an operator-machine
# user-profile path.
#
# This is the local complement to the CI `pii-guard.yml` workflow, which
# scans tracked FILE CONTENT and, as a server-side backstop, the commits
# being merged.  This hook runs the same commit scan on your machine, before
# anything reaches the remote (the 2026-06 leak was 17 `Co-authored-by:`
# gmail trailers in commit bodies).  Recurrence guard for the 2026-06 PII
# remediation.
#
# Enable once per clone (the hook is committed but git does not run hooks
# from a tracked directory automatically):
#
#     git config core.hooksPath scripts/git-hooks
#
# Matching lives in .github/scripts/pii_guard.py, which holds no identifier
# in readable form: personal identifiers are listed by sha256 digest in
# .github/pii-guard.hashes and user-profile paths are matched by shape.  An
# earlier version of this hook spelled the values as character-class regexes
# so the content scan would not flag the hook itself; that still published
# them to anyone who read this file.
set -euo pipefail

ZERO='0000000000000000000000000000000000000000'
GUARD="$(git rev-parse --show-toplevel)/.github/scripts/pii_guard.py"
PY="$(command -v python3 || command -v python || true)"
if [ -z "${PY}" ]; then
    echo "pre-push: BLOCKED — python3 is needed to run ${GUARD}." >&2
    exit 1
fi

fail=0

while read -r local_ref local_sha remote_ref remote_sha; do
    # Nothing to push for this ref (a branch delete).
    [ "${local_sha}" = "${ZERO}" ] && continue

    if [ "${remote_sha}" = "${ZERO}" ]; then
        # New branch on the remote: only the commits not already on a
        # remote-tracking branch, so shared history isn't re-scanned.
        revs=("${local_sha}" --not --remotes)
    else
        revs=("${remote_sha}..${local_sha}")
    fi

    # Author + committer identity AND the full message of every pushed
    # commit.  (File content is the CI guard's job.)
    if ! "${PY}" -I "${GUARD}" --commits "${revs[@]}" >&2; then
        fail=1
    fi
done

if [ "${fail}" -ne 0 ]; then
    echo "" >&2
    echo "pre-push: BLOCKED — a pushed commit's message or identity leaks" >&2
    echo "a personal identifier or operator path (see findings above)." >&2
    echo "Fix the author/committer (git config user.email) or amend the" >&2
    echo "message, then re-push." >&2
    exit 1
fi

exit 0
