#!/usr/bin/env bash
#
# regista commit-message identifier gate.
#
# The pre-commit hook scans staged file CONTENT. Commit messages were never
# scanned by anything — not by the hook, not by CI. That blind spot is not
# theoretical: a public repository carried work-domain identifiers in three
# commit messages, and two of those three were the commits that redacted the
# same identifiers from files. The message described what the diff removed.
#
# Activate (once per clone):   scripts/install-git-hooks.sh
#
# Denylist resolution is identical to pre-commit (see that hook for the order).
#
# No denylist: the gate decides from publication.toml. A repo declared PUBLIC is
# refused (exit 1) -- on a public repo the local hooks are the last prevention
# point, and CI only detects after the fact. A private-until-review repo stays a
# no-op so a fresh clone is not bricked. The ONLY bypass is the explicit
# GATE_ALLOW_NO_DENYLIST=1, which prints a warning every time it is used.
set -euo pipefail

repo_root="$(git rev-parse --show-toplevel)"
message_file="$1"

if [ -z "${REGISTA_FORBIDDEN_IDENTIFIERS:-}" ]; then
  for candidate in \
    "$repo_root/.identifiers-denylist.local" \
    "${HOME:-}/.config/agent-suite/forbidden-identifiers"; do
    if [ -f "$candidate" ]; then
      REGISTA_FORBIDDEN_IDENTIFIERS="$(cat "$candidate")"
      export REGISTA_FORBIDDEN_IDENTIFIERS
      break
    fi
  done
fi

no_denylist=0
denylist="${REGISTA_FORBIDDEN_IDENTIFIERS:-}"
if [ -z "${denylist//[[:space:]]/}" ]; then
  no_denylist=1
  if [ "${GATE_ALLOW_NO_DENYLIST:-}" = "1" ]; then
    echo "regista commit-msg: WARNING: identifier gate BYPASSED (GATE_ALLOW_NO_DENYLIST=1) -- no denylist, this message was NOT scanned." >&2
    exit 0
  fi
fi

python_bin="$repo_root/.venv/bin/python"
[ -x "$python_bin" ] || python_bin="$(command -v python3 || command -v python || true)"
if [ -z "$python_bin" ]; then
  echo "regista commit-msg: FATAL: no Python interpreter found; the identifier gate cannot run." >&2
  exit 1
fi

status=0
"$python_bin" "$repo_root/scripts/check_committed_identifiers.py" \
  --message-file "$message_file" || status=$?
if [ "$status" -ne 0 ] && [ "$no_denylist" -eq 1 ]; then
  echo "regista commit-msg: fix: put the denylist in ~/.config/agent-suite/forbidden-identifiers (or export REGISTA_FORBIDDEN_IDENTIFIERS); to bypass once, GATE_ALLOW_NO_DENYLIST=1 (warned)." >&2
fi
exit "$status"
