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

patterns=(
  "sk-"
  "whsec_"
  "Bearer "
  "Authorization:"
  "OPENAI_API_KEY"
  "YOCO_SECRET_KEY"
  "YOCO_WEBHOOK_SECRET"
  "WP_MASTER_KEY_B64"
  "APP_PASSWORD"
)

ignored_prefixes="^(vendor|node_modules|dist)/"

file_source() {
  if command -v git >/dev/null 2>&1 && [ -d .git ]; then
    git ls-files
  else
    find . \( -path './.git' -o -path './vendor' -o -path './node_modules' -o -path './dist' \) -prune \
      -o -type f -print
  fi
}

printf "Scanning tracked files for secrets...\n"
issue_count=0

while IFS= read -r file; do
  [[ -z "$file" ]] && continue
  file="${file#./}"
  if [[ "$file" =~ $ignored_prefixes ]]; then
    continue
  fi

  for pattern in "${patterns[@]}"; do
    if matches=$(grep -iIn -- "$pattern" -- "$file" 2>/dev/null); then
      if [[ -n "$matches" ]]; then
        printf "Secret candidate: %s\n%s\n" "$file" "$matches"
        issue_count=$((issue_count + 1))
      fi
    fi
  done

done < <(file_source)

if [[ $issue_count -gt 0 ]]; then
  printf "secret_scan: FAILED (%d issue(s) found)\n" "$issue_count"
  exit 1
fi

printf "secret_scan: PASSED\n"
