#!/usr/bin/env bash
# hooks/global/pre-commit — GLOBAL git hook (core.hooksPath for every
# repo on this host). Runs universal checks always, delegates to the
# repo's own enforcement when present, and chains the repo's installed
# .git/hooks/<name> so copy-installed hooks keep working.
#
# Layers, in order:
#   1. Universal: staged conflict markers, secret-looking material,
#      :latest image tags in staged compose/Dockerfiles.
#   2. Repo-local: scripts/check-rules.sh --fast  (if the repo ships it)
#   3. Repo chain: .git/hooks/pre-commit           (if present)
# Bypass: --no-verify in genuine emergencies ONLY, and note it in the
# repo JOURNAL the same day.
set -uo pipefail

REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || exit 0)"
FAIL=0

# --- 1. Universal checks on staged content -------------------------------
while IFS= read -r -d '' f; do
    # skip binary-looking blobs
    case "$f" in
        *.png|*.jpg|*.jpeg|*.gif|*.ico|*.woff|*.woff2|*.ttf|*.db|*.zip|*.gz) continue ;;
    esac
    [ -f "$REPO_ROOT/$f" ] || continue

    if grep -nE '^(<{7}( \S+)?|=======|>{7}( \S+)?)$' "$REPO_ROOT/$f" >/dev/null 2>    if grep -nE '^(<<<<<<<|=======|>>>>>>>)' "$REPO_ROOT/$f" >/dev/null 2>&1; then1; then
        echo "FAIL conflict markers staged in $f" >&2; FAIL=1
    fi
    case "$f" in
        *Dockerfile*|*docker-compose*|*compose*.y*ml)
            if grep -nE 'image:[[:space:]]*[A-Za-z0-9._/-]+:latest' "$REPO_ROOT/$f" >/dev/null 2>&1; then
                echo "FAIL :latest image tag in $f (pin digests or versions)" >&2; FAIL=1
            fi ;;
    esac
    if grep -nE '(sk-[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16}|-----BEGIN (RSA|EC|OPENSSH) PRIVATE KEY-----)' "$REPO_ROOT/$f" >/dev/null 2>&1; then
        echo "FAIL secret-looking material staged in $f (secrets live ONLY in ~/.creds)" >&2; FAIL=1
    fi
done < <(git diff --cached --name-only -z 2>/dev/null)

# --- 2. Repo-local rule engine, when adopted -----------------------------
if [ -x "$REPO_ROOT/scripts/check-rules.sh" ]; then
    if ! (cd "$REPO_ROOT" && bash scripts/check-rules.sh --fast --quiet); then
        echo "FAIL repo-local check-rules.sh (fast)" >&2; FAIL=1
    fi
fi

# --- 3. Chain the repo's own installed hook ------------------------------
if [ -x "$REPO_ROOT/.git/hooks/pre-commit" ]; then
    if ! "$REPO_ROOT/.git/hooks/pre-commit"; then
        echo "FAIL repo .git/hooks/pre-commit" >&2; FAIL=1
    fi
fi

exit "$FAIL"
