#!/usr/bin/env bash
set -Eeuo pipefail
REPO="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd -P)"
cd "$REPO"
python3 - <<'PY'
from __future__ import annotations
import os
import re
import subprocess
from pathlib import Path

root = Path.cwd()
forbidden_exact = {"config.local.json", ".env"}
forbidden_prefixes = (".secrets/", ".tunnel/", "chatgpt-computer-mcp-activation/")
forbidden_suffixes = (".service.local", ".activation", ".credentials", ".secret", ".token")
patterns = [
    ("OpenAI/API-style secret key", re.compile(rb"\bsk-[A-Za-z0-9_-]{20,}\b")),
    ("GitHub token", re.compile(rb"\bgh[pousr]_[A-Za-z0-9]{20,}\b")),
    ("private key material", re.compile(rb"-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----")),
    ("AWS access key", re.compile(rb"\bAKIA[0-9A-Z]{16}\b")),
    ("OpenAI tunnel id", re.compile(rb"\btunnel_[0-9a-f]{32}\b")),
]
sample_tunnel = b"tunnel_0123456789abcdef0123456789abcdef"

try:
    out = subprocess.check_output(["git", "ls-files", "-z"], stderr=subprocess.DEVNULL)
    paths = [Path(x.decode()) for x in out.split(b"\0") if x]
except Exception:
    paths = []

if not paths:
    skip_dirs = {".git", "node_modules", "dist", "coverage", ".secrets", ".tunnel", "screenshots"}
    for base, dirs, files in os.walk(root):
        dirs[:] = [d for d in dirs if d not in skip_dirs]
        for name in files:
            rel = (Path(base) / name).relative_to(root)
            if str(rel) == "config.local.json":
                continue
            paths.append(rel)

problems: list[str] = []
for rel in sorted(set(paths), key=str):
    s = rel.as_posix()
    if s in forbidden_exact or s.startswith(forbidden_prefixes) or s.endswith(forbidden_suffixes):
        problems.append(f"forbidden local/credential artifact is repository-controlled: {s}")
        continue
    path = root / rel
    try:
        data = path.read_bytes()
    except OSError:
        continue
    if b"\0" in data[:8192]:
        continue
    for label, pattern in patterns:
        matches = list(pattern.finditer(data))
        if label == "OpenAI tunnel id":
            matches = [m for m in matches if m.group(0) != sample_tunnel]
        if matches:
            problems.append(f"potential {label} found in {s} (value suppressed)")

if problems:
    print("SECRET CHECK: FAIL", flush=True)
    for problem in problems:
        print(f"- {problem}", flush=True)
    raise SystemExit(1)
print(f"SECRET CHECK: PASS ({len(paths)} repository-controlled files scanned; values never printed)")
PY
