#!/usr/bin/env bash
# Secret gate: block any commit whose staged diff contains live-secret shapes.
# This repo is pushed to a Gitea remote; anything committed is instantly visible
# on the fleet. Deliberate override: ALLOW_SECRETS=1 git commit ...
set -uo pipefail

staged=$(git diff --cached --diff-filter=ACM -U0 -- '*.md' '*.yml' '*.yaml' '*.json' '*.toml' '*.sh' '*.ts' '*.js')
[ -z "$staged" ] && exit 0

patterns='sk-[A-Za-z0-9]{18,}|ghp_[A-Za-z0-9]{36}|github_pat_[A-Za-z0-9_]{22,}|glpat-[A-Za-z0-9_-]{20}|xox[baprs]-[A-Za-z0-9-]{10,}|AKIA[A-Z0-9]{16}|ASIA[A-Z0-9]{16}|BEGIN [A-Z ]*PRIVATE KEY|aes_[A-Za-z0-9/+]{40}|eyJ[A-Za-z0-9_-]{20,}\.ey'

hits=$(printf '%s\n' "$staged" | grep -Ei "$patterns" || true)
if [ -n "${ALLOW_SECRETS:-}" ]; then
  [ -n "$hits" ] && printf 'secret-gate: ALLOW_SECRETS set, allowing %s secret-shaped string(s) through.\n' "$(printf '%s\n' "$hits" | wc -l)"
  exit 0
fi

if [ -n "$hits" ]; then
  {
    echo "SECRET GATE: staged diff contains $(printf '%s\n' "$hits" | wc -l) secret-shaped string(s):"
    printf '%s\n' "$hits" | sed 's/^/  /'
    echo "Fix it, or override deliberately: ALLOW_SECRETS=1 git commit ..."
  } >&2
  exit 1
fi
exit 0
