#!/usr/bin/env bash
#
# pre-commit — sibling boundary guard (v1) + gitleaks secret scan.
#
# 1. Boundary guard: denies staged changes matching another sibling's owned
#    patterns per .githooks/boundary-patterns.txt.
# 2. Gitleaks: scans staged content against .gitleaks.toml for leaked secrets.
#    Install: sudo apt install gitleaks  (Ubuntu 24.04 universe)
#
# Bypass:
#   git commit --no-verify     — bypasses both checks (operator honor rule)
#   SKIP_LEAKS=1 git commit    — bypasses gitleaks only (boundary guard still runs)

set -euo pipefail

# BEGIN sibling-boundary-guard v1 — do not edit between markers; managed by BOUNDARY_GUARD_V1.md
PATTERNS="$(git rev-parse --show-toplevel)/.githooks/boundary-patterns.txt"
if [ -f "$PATTERNS" ]; then
  REPO=$(basename "$(git rev-parse --show-toplevel)")
  FILTERED=$(mktemp)
  grep -v "^\[$REPO\]" "$PATTERNS" | grep -v '^#' | grep -v '^$' | sed 's/^\[[^]]*\][[:space:]]*//' > "$FILTERED"
  # Filter to added lines only; deleting a boundary-crossing symbol should not
  # be denied. `|| true` protects against pipefail when no `+` lines exist
  # (pure-deletion or rename-only commits).
  DIFF=$(git diff --cached | grep '^+' | grep -v '^+++' || true)
  MATCH=$(printf '%s\n' "$DIFF" | grep -Ef "$FILTERED" | head -3 || true)
  rm -f "$FILTERED"
  if [ -n "$MATCH" ]; then
    cat >&2 <<'EOF'
sibling-boundary-guard: staged changes match another sibling's owned patterns.
EOF
    printf '\nMatched (first 3):\n%s\n\n' "$MATCH" >&2
    cat >&2 <<'EOF'
See .githooks/boundary-patterns.txt.
Delegate via that sibling's CLI instead of reimplementing.

Intentional (e.g. moving a primitive between siblings):
  git commit --no-verify + update .githooks/boundary-patterns.txt in the same PR.
EOF
    exit 1
  fi
fi
# END sibling-boundary-guard v1

# BEGIN gitleaks secret scan
if [[ "${SKIP_LEAKS:-0}" != "1" ]]; then
  if ! command -v gitleaks >/dev/null 2>&1; then
    echo "[pre-commit] gitleaks not found. Install: sudo apt install gitleaks" >&2
    echo "[pre-commit] Or skip with: SKIP_LEAKS=1 git commit" >&2
    exit 1
  fi
  cd "$(git rev-parse --show-toplevel)"
  gitleaks protect --staged --no-banner --redact
else
  echo "[pre-commit] SKIP_LEAKS=1 — skipping gitleaks scan." >&2
fi
# END gitleaks secret scan

exit 0
