#!/usr/bin/env python3
"""Tiny secret scanner for a Git repository: working tree AND full history (lesson OPS-250-L04).

It is a teaching tool, not a replacement for a real scanner (e.g. your Git host's secret scanning):
it only knows a few common patterns. It prints WHERE a match is (file, commit), never the full value.

    python scan_secrets.py /path/to/repo
"""
import re
import subprocess
import sys

PATTERNS = {
    "private key block": re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"),
    "assignment of a token/key/secret/password": re.compile(r"(?i)\b[A-Z0-9_]*(TOKEN|SECRET|PASSWORD|API_KEY|APIKEY)[A-Z0-9_]*\s*[=:]\s*['\"]?([^\s'\"#]{8,})"),
    "AWS access key id shape": re.compile(r"\bAKIA[0-9A-Z]{16}\b"),
    "GitHub token shape": re.compile(r"\bgh[pousr]_[A-Za-z0-9]{30,}\b"),
    "OpenAI-style key shape": re.compile(r"\bsk-[A-Za-z0-9_-]{20,}\b"),
}
ALLOW = re.compile(r"(?i)(example|placeholder|changeme|change-me|your[-_]|<[^>]+>|\$\{|os\.environ|getenv)")


def mask(v):
    return v[:3] + "…" + f"({len(v)} chars)"


def scan_text(text, where, hits):
    for n, line in enumerate(text.splitlines(), 1):
        if ALLOW.search(line):
            continue
        for name, rx in PATTERNS.items():
            m = rx.search(line)
            if m:
                val = m.group(m.lastindex) if m.lastindex else m.group(0)
                hits.append(f"{where}:{n}: {name}: {mask(val)}")


def main(repo):
    hits = []
    files = subprocess.run(["git", "-C", repo, "ls-files"], capture_output=True, text=True, check=True).stdout.split()
    for f in files:
        try:
            scan_text(open(f"{repo}/{f}", encoding="utf-8", errors="ignore").read(), f"working tree {f}", hits)
        except OSError:
            pass
    log = subprocess.run(["git", "-C", repo, "log", "--all", "-p", "--format=@@COMMIT %h %s"],
                         capture_output=True, text=True, check=True).stdout
    commit = "?"
    for line in log.splitlines():
        if line.startswith("@@COMMIT "):
            commit = line[9:]
        elif line.startswith("+") and not line.startswith("+++"):
            scan_text(line[1:], f"history {commit}", hits)
    print("\n".join(hits) if hits else "no matches (this does NOT prove the repository is clean)")
    return 1 if hits else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1] if len(sys.argv) > 1 else "."))
