#!/bin/sh
# redactkit pre-commit hook.
#
# Install:   cp hooks/pre-commit .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit
# Skip once: git commit --no-verify
#
# Scans the staged diff, not the working tree, so it sees exactly what you are
# about to commit. Nothing leaves the machine.

REDACTKIT="${REDACTKIT:-redactkit}"

if ! command -v "$REDACTKIT" >/dev/null 2>&1; then
  echo "pre-commit: redactkit not on PATH; set REDACTKIT=/path/to/bin/redactkit.mjs" >&2
  exit 0   # never block a commit because the hook itself is misconfigured
fi

# Only added lines can introduce a secret; removing one is the fix, not the crime.
staged=$(git diff --cached --unified=0 | grep '^+' | grep -v '^+++')
[ -z "$staged" ] && exit 0

report=$(printf '%s\n' "$staged" | "$REDACTKIT" --check --json 2>/dev/null)
status=$?

if [ $status -eq 1 ]; then
  echo "" >&2
  echo "  commit blocked: redactkit found credentials in the staged diff" >&2
  echo "" >&2
  printf '%s\n' "$staged" | "$REDACTKIT" --check -o /dev/null 2>&1 >/dev/null | sed 's/^/  /' >&2
  echo "" >&2
  echo "  Review the staged lines, then either remove the secret or commit with" >&2
  echo "  --no-verify if this is a false positive. If it IS a false positive," >&2
  echo "  please say so: it is the only way the detectors get better." >&2
  echo "" >&2
  exit 1
fi

exit 0
