#!/bin/bash
# Gitea server-side pre-receive hook: reject pushes that introduce secrets.
#
# This runs only on client pushes (HTTP/SSH), not on pull-mirror sync
# (those use git fetch and bypass pre-receive). Safe to install globally.
#
# Install: see /workspace/gitea/hygiene/INSTALL.md
set -u

GITLEAKS="${GITLEAKS_BIN:-/usr/local/bin/gitleaks}"
ZERO="0000000000000000000000000000000000000000"

if [ ! -x "$GITLEAKS" ]; then
  echo "gitleaks is not installed at $GITLEAKS; refusing push." >&2
  echo "Install gitleaks or temporarily move this hook aside." >&2
  exit 1
fi

# GIT_DIR is set by Gitea/git to the bare repository being pushed to.
SOURCE="${GIT_DIR:-.}"
failed=0

while read -r oldrev newrev refname; do
  [ -n "${newrev:-}" ] || continue

  # Branch or tag deletion: nothing new to scan.
  if [ "$newrev" = "$ZERO" ]; then
    continue
  fi

  if [ "$oldrev" = "$ZERO" ]; then
    # New ref: scan the tip (and reachable history). --log-opts limits
    # the walk; for a new branch this may include earlier commits already
    # on other refs, which is conservative and correct.
    log_opts="$newrev"
  else
    log_opts="$oldrev..$newrev"
  fi

  report="$(mktemp)"
  if ! "$GITLEAKS" detect \
      --source "$SOURCE" \
      --log-opts="$log_opts" \
      --redact \
      --no-banner \
      --report-format json \
      --report-path "$report" \
      --exit-code 1 >/dev/null 2>&1; then
    echo "Push rejected: gitleaks found secrets in ${refname}." >&2
    echo "Rebase or filter the commits, remove the secrets, and try again." >&2
    echo "Rule / file summary (secret values redacted):" >&2
    # Print only rule + file + line, never the secret itself.
    python3 - "$report" << 'PY' >&2 || true
import json, sys
path = sys.argv[1]
try:
    with open(path) as f:
        data = json.load(f)
except Exception:
    sys.exit(0)
if not data:
    sys.exit(0)
for item in data:
    rule = item.get("RuleID") or item.get("Rule") or "unknown-rule"
    file = item.get("File") or item.get("FilePath") or "unknown-file"
    line = item.get("StartLine") or item.get("StartLineNumber") or "?"
    commit = (item.get("Commit") or "")[:12]
    print(f"  - {rule}: {file}:{line} commit {commit}")
PY
    failed=1
  fi
  rm -f "$report"
done

exit "$failed"
