#!/usr/bin/env bash
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
cd "$REPO_ROOT"

REPORT_PATH="${1:-docs/reports/2026-02-17-history-scan.md}"
NOW_UTC="$(date -u +"%Y-%m-%d %H:%M:%S UTC")"

mkdir -p "$(dirname "$REPORT_PATH")"

{
  echo "# Git History Security Scan"
  echo
  echo "- Generated: ${NOW_UTC}"
  echo "- Repository: payload-cms"
  echo

  echo "## Summary"
  echo

  if git ls-files --error-unmatch backup.sql >/dev/null 2>&1; then
    echo "- \`backup.sql\` is still tracked in current HEAD (critical)."
  else
    echo "- \`backup.sql\` is not tracked in current HEAD."
  fi

  backup_history="$(git log --all --date=short --pretty=format:'%h %ad %s' -- backup.sql || true)"
  if [[ -n "${backup_history}" ]]; then
    echo "- \`backup.sql\` exists in git history and must be treated as potentially sensitive."
  else
    echo "- No git history entries found for \`backup.sql\`."
  fi

  if command -v gitleaks >/dev/null 2>&1; then
    echo "- \`gitleaks\` available: yes (run with: \`gitleaks git --redact --verbose\`)."
  else
    echo "- \`gitleaks\` available: no (install recommended for full-history secret scanning)."
  fi

  echo
  echo "## backup.sql Commit History"
  echo

  if [[ -n "${backup_history}" ]]; then
    echo '```text'
    echo "${backup_history}"
    echo '```'
  else
    echo "_No entries found._"
  fi

  echo
  echo "## Recommended Actions"
  echo
  echo "1. Rotate DB credentials if \`backup.sql\` contained production or staging data."
  echo "2. Rotate SMTP/API/OAuth secrets if dumps included integration credentials."
  echo "3. If required by compliance, rewrite history for \`backup.sql\` (e.g. \`git filter-repo\`) and force-push."
  echo "4. Enable periodic full-history scans in CI using gitleaks."
} > "$REPORT_PATH"

echo "History scan report written to ${REPORT_PATH}"
