#!/usr/bin/env python3
"""Run a packaged T3 Code AppImage under a subreaper, trigger a main-process exit, and
report how every descendant ended (exit code or signal), plus when the FUSE mount went away.

usage: driver.py <appimage> <scenario: quit|display-loss|sigkill-main|sigsegv-main> <outdir>
"""
import ctypes, os, signal, subprocess, sys, time, json, resource
resource.setrlimit(resource.RLIMIT_CORE, (0, 0))

appimage, scenario, outdir = sys.argv[1], sys.argv[2], sys.argv[3]
os.makedirs(outdir, exist_ok=True)
libc = ctypes.CDLL("libc.so.6", use_errno=True)
libc.prctl(36, 1, 0, 0, 0)  # PR_SET_CHILD_SUBREAPER

home = os.path.join(outdir, "home")
os.makedirs(home, exist_ok=True)
display = ":%d" % (90 + os.getpid() % 50)
xvfb = subprocess.Popen(["Xvfb", display, "-screen", "0", "1280x800x24", "-nolisten", "tcp"],
                        stderr=subprocess.DEVNULL)
time.sleep(1.5)
rec = subprocess.Popen(["ffmpeg", "-y", "-loglevel", "error", "-f", "x11grab", "-framerate", "10", "-video_size", "1280x800", "-i", display, "-c:v", "libx264", "-preset", "ultrafast", "-crf", "28", "-pix_fmt", "yuv420p", os.path.join(outdir, "desktop.mp4")], stderr=open(os.path.join(outdir, "recording.log"), "w"))
env = {k: v for k, v in os.environ.items() if not k.startswith(("T3CODE", "WAYLAND", "VITE_"))}
env.update(DISPLAY=display, HOME=home, XDG_CONFIG_HOME=home + "/.config",
           XDG_DATA_HOME=home + "/.local/share", XDG_CACHE_HOME=home + "/.cache",
           XDG_STATE_HOME=home + "/.local/state", T3CODE_HOME=home + "/.t3",
           T3CODE_DEV_SEED="0", ELECTRON_ENABLE_LOGGING="1")
env.pop("XDG_RUNTIME_DIR", None) if False else None
log = open(os.path.join(outdir, "app.log"), "w")
t0 = time.monotonic()
def ts(): return "%7.3f" % (time.monotonic() - t0)
app = subprocess.Popen([appimage, "--no-sandbox", "--disable-gpu"], env=env, stdout=log, stderr=subprocess.STDOUT)

names = {}
def read(p):
    try:
        with open(p) as f: return f.read()
    except OSError: return None
def descendants():
    out = []
    for d in os.listdir("/proc"):
        if not d.isdigit(): continue
        st = read("/proc/%s/stat" % d)
        if st is None: continue
        ppid = int(st[st.rindex(")") + 2:].split()[1])
        out.append((int(d), ppid))
    tree = {app.pid}; changed = True
    while changed:
        changed = False
        for pid, ppid in out:
            if ppid in tree and pid not in tree:
                tree.add(pid); changed = True
    # after reparenting, orphans have ppid == us
    for pid, ppid in out:
        if ppid == os.getpid() and pid not in (xvfb.pid, rec.pid):
            tree.add(pid)
    return tree
def label(pid):
    cmd = (read("/proc/%d/cmdline" % pid) or "").split("\0")
    exe = os.path.basename(cmd[0]) if cmd and cmd[0] else "?"
    t = next((a for a in cmd if a.startswith("--type=")), "")
    if "bin.mjs" in " ".join(cmd) or "server" in " ".join(cmd[1:2]): exe += " (server)"
    return (exe + " " + t).strip()

def mounts():
    return [l.split()[1] for l in (read("/proc/mounts") or "").splitlines() if ".mount_" in l]

deadline = time.monotonic() + 120
ready = False
while time.monotonic() < deadline:
    for p in descendants():
        if p not in names: names[p] = label(p)
    if any("t3-resource-monitor" in n for n in names.values()):
        ready = True; break
    time.sleep(0.5)
time.sleep(15)
for p in descendants():
    names.setdefault(p, label(p))
main = next((p for p, n in names.items() if n.split()[0] in ("t3code", "t3-code", "T3 Code", "@t3toolsdesktop") or (
    "--type=" not in n and ".mount_" in (read("/proc/%d/cmdline" % p) or "") and "AppRun" not in n and "resource" not in n and "server" not in n)), None)
# pick main: an electron process inside the mount with no --type and whose children include --type= processes
cands = [p for p, n in names.items() if "--type=" not in n and ".mount_" in (os.readlink("/proc/%d/exe" % p) if os.path.exists("/proc/%d/exe" % p) else "")]
report = {"scenario": scenario, "ready": ready, "mountsBefore": mounts(), "events": [], "tree": {}}
for p in sorted(descendants()):
    report["tree"][p] = {"label": names.get(p), "exe": (os.readlink("/proc/%d/exe" % p) if os.path.exists("/proc/%d/exe" % p) else None),
                         "cmd": (read("/proc/%d/cmdline" % p) or "").replace("\0", " ")[:200]}
# main = candidate whose parent is not another candidate
def ppid(p):
    st = read("/proc/%d/stat" % p); return int(st[st.rindex(")") + 2:].split()[1]) if st else -1
mainpid = next((p for p in cands if ppid(p) not in cands and "resource" not in report["tree"][p]["cmd"] and "--type" not in report["tree"][p]["cmd"] and report["tree"][p]["exe"] and not report["tree"][p]["exe"].endswith("node")), None)
report["mainPid"] = mainpid
report["events"].append((ts(), "trigger " + scenario))
if scenario == "display-loss":
    xvfb.kill()
elif scenario == "sigkill-main":
    os.kill(mainpid, signal.SIGKILL)
elif scenario == "sigsegv-main":
    os.kill(mainpid, signal.SIGSEGV)
elif scenario == "quit":
    os.kill(mainpid, signal.SIGTERM)

had_mount = bool(mounts())
end = time.monotonic() + 40
while time.monotonic() < end:
    if had_mount and not mounts():
        report["events"].append((ts(), "mount gone")); had_mount = False
    try:
        pid, status = os.waitpid(-1, os.WNOHANG)
    except ChildProcessError:
        break
    if pid == 0:
        time.sleep(0.005); continue
    if pid in (xvfb.pid, rec.pid): continue
    how = ("signal %s" % signal.Signals(os.WTERMSIG(status)).name) if os.WIFSIGNALED(status) else "exit %d" % os.WEXITSTATUS(status)
    report["events"].append((ts(), "%d %s: %s" % (pid, names.get(pid, report["tree"].get(pid, {}).get("label", "?")), how)))
if rec.poll() is None:
    rec.send_signal(signal.SIGINT)
    rec.wait()
if xvfb.poll() is None: xvfb.kill()
xvfb.wait()
json.dump(report, open(os.path.join(outdir, "report.json"), "w"), indent=1)
for e in report["events"]: print(*e)
print("mainPid", mainpid)
