#!/usr/bin/env bash
# Reject commit messages containing a GitHub closing keyword next to an issue
# reference. This is the *prevention* half of the guard: a commit pushed
# directly to `main` never passes through a PR, so CI can only notice it after
# the issue has already closed. See scripts/check_closing_keywords.py.
#
# Install:  ./scripts/install-hooks.sh
# Bypass:   ALLOW_CLOSING_KEYWORD=1 git commit ...
set -euo pipefail

# The documented explicit bypass works even when Python is unavailable.
[ "${ALLOW_CLOSING_KEYWORD:-}" = "1" ] && exit 0

repo_root="$(git rev-parse --show-toplevel)"
checker="$repo_root/scripts/check_closing_keywords.py"

# Never block a commit because the guard itself is missing (e.g. checking out
# an older revision). Fail open here; CI is the backstop.
[ -f "$checker" ] || exit 0

# Only ask the checker to apply git's comment/scissors cleanup when git will
# actually perform it. Under `whitespace` or `verbatim`, `#` lines survive into
# the stored message and GitHub parses them, so they must be scanned.
cleanup="$(git config --get commit.cleanup || echo default)"
case "$cleanup" in
  default | strip) git_comments="--git-comments" ;;
  scissors)        git_comments="--git-comments" ;;
  *)               git_comments="" ;;
esac

# Use the first Python that actually runs, not merely the first on PATH. On
# Windows, `python3` is usually the Microsoft Store alias: it exists, prints an
# install hint and exits non-zero, which under `set -e` rejected every commit
# without scanning anything. Git for Windows ships no Python of its own.
python=""
for candidate in python3 python; do
  if "$candidate" -c 'import sys; sys.exit(sys.version_info < (3, 8))' >/dev/null 2>&1; then
    python="$candidate"
    break
  fi
done
# Never accept an unchecked commit merely because interpreter discovery failed.
if [ -z "$python" ]; then
  echo "commit-msg: no usable Python >=3.8 found; commit rejected. Install Python and add python3 or python to PATH, then retry. Explicit bypass: ALLOW_CLOSING_KEYWORD=1 git commit ..." >&2
  exit 1
fi

# shellcheck disable=SC2086
"$python" "$checker" "$1" $git_comments \
  --label "commit message" \
  --bypass-hint "ALLOW_CLOSING_KEYWORD=1 git commit ..."
