#!/usr/bin/env bash
# repo-secrets <repo> scan|add|ignore|list|ignored [<path-or-glob>...]
# guard.py already denies a fixed, global set of secret-shaped filenames (.env*, *.pem/*.key,
# *credentials*.json, secrets.json/yaml/toml) for every repo. That set cannot grow to cover every
# company's own naming (service-account.json, .npmrc, id_rsa, .aws/credentials, apikey.txt) without
# becoming unbounded, so per-repo names are handled instead as DENY RULES you write yourself into
# registry/rules.yaml — the same gitignored, deny-only extension point documented in
# docs/rules.md#rules-of-your-own.
#
# IMPORTANT: `add` is destructive, not bookkeeping. It writes deny rules that make the named
# file(s) unreadable (and unwritable) to every future Claude Code session in this repo. Most
# scan candidates turn out to be ordinary source (password.py, token_store.py, ...), not secrets —
# review before adding. To dismiss a false positive WITHOUT denying it, use `ignore` instead.
#
#   repo-secrets <repo> scan                    candidate filenames, one per line, by name only,
#                                                 excluding anything already `ignore`d for this repo
#   repo-secrets <repo> add <path-or-glob>...   DENY future Read/Edit/Write/Bash-cat of each path —
#                                                 makes it unreadable to every future session
#   repo-secrets <repo> ignore <path-or-glob>...  mark a candidate reviewed-and-not-a-secret; `scan`
#                                                 stops surfacing it, no deny rule is written
#   repo-secrets <repo> list                    paths already denied (via `add`) for this repo
#   repo-secrets <repo> ignored                 paths already dismissed (via `ignore`) for this repo
source "$(python3 -c 'import os,sys;print(os.path.dirname(os.path.realpath(sys.argv[1])))' "$0")/lib.sh"

repo="${1:-}"; sub="${2:-}"
[ -n "$sub" ] && [ -n "$repo" ] || die "usage: repo-secrets <repo> scan|add|ignore|list|ignored [<path-or-glob>...]"
repo_exists "$repo"
shift 2
RULES="$REGISTRY/rules.yaml"
IGNORED="$REGISTRY/secrets-ignored.yaml"

# Filename shapes the built-in guard does NOT already cover — no point declaring what is already
# denied everywhere. Case-insensitive, filename-only: this never reads what is inside a file.
CANDIDATE_RE='(^|/)(\.npmrc|\.netrc|id_rsa[^/]*|id_ed25519[^/]*|id_ecdsa[^/]*|[^/]*\.(keystore|jks)|service[-_]?account[^/]*\.json|[^/]*credentials[^/]*|[^/]*api[-_]?key[^/]*|[^/]*password[^/]*|[^/]*token[^/]*|\.aws/[^/]*|\.ssh/id_[^/]*)$'

case "$sub" in
  scan)
    repo_dir="$REPOS/$repo"
    ignored_now=$({ [ -f "$IGNORED" ] && python3 -c '
import sys, re
repo = sys.argv[1]
text = open(sys.argv[2]).read()
in_repo = False
for line in text.splitlines():
    m = re.match(r"^  ([\w.-]+):\s*$", line)
    if m:
        in_repo = (m.group(1) == repo)
        continue
    if in_repo:
        m2 = re.match(r"^    - path: \"(.*)\"", line)
        if m2:
            print(m2.group(1))
' "$repo" "$IGNORED"; } || true)
    { git -C "$repo_dir" ls-files
      git -C "$repo_dir" status --porcelain --ignored -z | tr '\0' '\n' | sed -n 's/^!! //p'
    } | { grep -iE "$CANDIDATE_RE" || true; } | sort -u \
      | { if [ -n "$ignored_now" ]; then grep -vFxf <(printf '%s\n' "$ignored_now"); else cat; fi; }
    ;;

  list)
    [ -f "$RULES" ] || exit 0
    # the -read rule of each declared pattern carries `when: { tool: Read, path: "<path>" }`;
    # pull the path out of just those, so a pattern declared once shows once, not six times
    { grep -A1 "^  - id: secret-$repo-[0-9]*-read\$" "$RULES" 2>/dev/null || true; } \
      | sed -n 's/.*path: "\(.*\)" }.*/\1/p' | sort -u
    ;;

  ignore)
    [ $# -gt 0 ] || die "usage: repo-secrets <repo> ignore <path-or-glob> [<path-or-glob>...]"
    if [ ! -f "$IGNORED" ]; then
      cat > "$IGNORED" <<'EOT'
# Candidates from `repo-secrets scan` reviewed and dismissed as NOT secrets, per repo. This writes
# no deny rule and does not touch registry/rules.yaml -- `ignore` only silences `scan` (and lane
# doctor's advisory, which re-runs scan) for this path. Gitignored, like registry/rules.yaml.
repos:
EOT
    fi
    for path in "$@"; do
      if grep -qF "    - path: \"$path\"" "$IGNORED" 2>/dev/null; then
        echo "  already ignored, skipping: $path"
        continue
      fi
      # `ignore` never touches an existing deny rule -- but the success message below claims
      # "not denied", which would be false for a path `add` already covered. Warn instead of
      # printing that false claim; still record it, since dismissing the doctor advisory for a
      # path that's already denied is still a reasonable thing to want.
      already_denied=0
      if grep -qF "\"$path\"" "$RULES" 2>/dev/null || grep -qE "path: '?${path//\//\\/}'?" "$RULES" 2>/dev/null; then
        already_denied=1
      fi
      if ! grep -qF "  $repo:" "$IGNORED" 2>/dev/null; then
        printf '  %s:\n' "$repo" >> "$IGNORED"
      fi
      python3 - "$IGNORED" "$repo" "$path" <<'PY'
import sys
ignored_file, repo, path = sys.argv[1:4]
lines = open(ignored_file).read().splitlines(keepends=True)
out = []
inserted = False
in_repo = False
for line in lines:
    if not inserted:
        if line.rstrip("\n") == f"  {repo}:":
            in_repo = True
        elif in_repo and line.startswith("  ") and not line.startswith("    ") and line.strip():
            out.append(f'    - path: "{path}"\n')
            inserted = True
    out.append(line)
if not inserted:
    out.append(f'    - path: "{path}"\n')
open(ignored_file, "w").write("".join(out))
PY
      if [ "$already_denied" = 1 ]; then
        echo "  recorded as reviewed: $path (it is ALREADY DENIED via an earlier \`add\` -- ignore does not undo that, run \`repo-secrets $repo add\` again to see the existing rules, or remove them from registry/rules.yaml by hand to actually allow it)"
      else
        echo "  ignored (dismissed, not denied): $path"
      fi
    done
    ;;

  ignored)
    [ -f "$IGNORED" ] || exit 0
    python3 -c '
import sys, re
repo = sys.argv[1]
text = open(sys.argv[2]).read()
in_repo = False
for line in text.splitlines():
    m = re.match(r"^  ([\w.-]+):\s*$", line)
    if m:
        in_repo = (m.group(1) == repo)
        continue
    if in_repo:
        m2 = re.match(r"^    - path: \"(.*)\"", line)
        if m2:
            print(m2.group(1))
' "$repo" "$IGNORED"
    ;;

  add)
    [ $# -gt 0 ] || die "usage: repo-secrets add <repo> <path-or-glob> [<path-or-glob>...]"
    if [ ! -f "$RULES" ]; then
      cat > "$RULES" <<'EOT'
# This control plane's own rules, on top of the ones guard.py ships with. Deny-only, checked
# before the built-ins. It is gitignored — see docs/rules.md#rules-of-your-own.
rules:
EOT
    fi
    # continue the per-repo counter past whatever is already declared, so re-running `add` never
    # collides with existing rule ids
    n=$(grep -oE "id: secret-$repo-[0-9]+-read" "$RULES" 2>/dev/null | grep -oE '[0-9]+' | sort -n | tail -1) || true
    n=${n:-0}
    for path in "$@"; do
      if grep -qF "\"$path\"" "$RULES" 2>/dev/null || grep -qE "path: '?${path//\//\\/}'?" "$RULES" 2>/dev/null; then
        echo "  already declared, skipping: $path"
        continue
      fi
      n=$((n+1))
      ref="memory/$repo/MEMORY.md"
      # a literal (regex-escaped) substring of the path, for the Bash `matches` rule
      esc=$(python3 -c 'import re,sys;print(re.escape(sys.argv[1]))' "$path")
      {
        printf '  - id: secret-%s-%s-read\n' "$repo" "$n"
        printf '    when: { tool: Read, path: "%s" }\n' "$path"
        printf '    deny: "%s was denied as a secret/credential file for this repo (registry/rules.yaml) -- unreadable to every future session."\n' "$path"
        printf '    ref: %s\n' "$ref"
        printf '    example: { path: "repos/%s/%s" }\n\n' "$repo" "$path"

        printf '  - id: secret-%s-%s-edit\n' "$repo" "$n"
        printf '    when: { tool: Edit, path: "%s" }\n' "$path"
        printf '    deny: "%s was denied as a secret/credential file for this repo (registry/rules.yaml) -- unreadable to every future session."\n' "$path"
        printf '    ref: %s\n' "$ref"
        printf '    example: { path: "repos/%s/%s" }\n\n' "$repo" "$path"

        printf '  - id: secret-%s-%s-write\n' "$repo" "$n"
        printf '    when: { tool: Write, path: "%s" }\n' "$path"
        printf '    deny: "%s was denied as a secret/credential file for this repo (registry/rules.yaml) -- unreadable to every future session."\n' "$path"
        printf '    ref: %s\n' "$ref"
        printf '    example: { path: "repos/%s/%s" }\n\n' "$repo" "$path"

        printf '  - id: secret-%s-%s-multiedit\n' "$repo" "$n"
        printf '    when: { tool: MultiEdit, path: "%s" }\n' "$path"
        printf '    deny: "%s was denied as a secret/credential file for this repo (registry/rules.yaml) -- unreadable to every future session."\n' "$path"
        printf '    ref: %s\n' "$ref"
        printf '    example: { path: "repos/%s/%s" }\n\n' "$repo" "$path"

        printf '  - id: secret-%s-%s-notebookedit\n' "$repo" "$n"
        printf '    when: { tool: NotebookEdit, path: "%s" }\n' "$path"
        printf '    deny: "%s was denied as a secret/credential file for this repo (registry/rules.yaml) -- unreadable to every future session."\n' "$path"
        printf '    ref: %s\n' "$ref"
        printf '    example: { path: "repos/%s/%s" }\n\n' "$repo" "$path"

        printf '  - id: secret-%s-%s-bash\n' "$repo" "$n"
        printf '    when: { tool: Bash, matches: '"'"'%s'"'"' }\n' "$esc"
        printf '    deny: "%s was denied as a secret/credential file for this repo (registry/rules.yaml) -- unreadable to every future session."\n' "$path"
        printf '    ref: %s\n' "$ref"
        printf '    example: "cat repos/%s/%s"\n\n' "$repo" "$path"
      } >> "$RULES"
      echo "  denied (unreadable to future sessions): $path"
    done
    ;;

  *) die "usage: repo-secrets scan|add|ignore|list|ignored <repo> [<path-or-glob>...]" ;;
esac
