import os, sys, subprocess, datetime
from pathlib import Path

# Usage: python3 driver.py <checkout> <output-root> <label>
checkout, root, label = map(Path, sys.argv[1:])
run = root / (str(label) + "-" + datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%dT%H%M%S%f"))
run.mkdir(parents=True)
env = os.environ.copy()
for key in list(env):
    if key.startswith("T3CODE_") or key in ("T3_HOME", "T3CODE_HOME"):
        env.pop(key)
env.update(HOME=str(run / "home"), XDG_CONFIG_HOME=str(run / "config"), XDG_RUNTIME_DIR=str(run / "runtime"), DBUS_SESSION_BUS_ADDRESS="unix:path=" + str(run / "no-bus"), T3CODE_DEV_SEED="0", NO_COLOR="1", FORCE_COLOR="0")
sha = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=checkout, text=True).strip()
text = "Linux CLI | built bundle | non-TTY stdin | isolated HOME, XDG and user bus\nFresh synthetic T3 home: ./t3-other\nCommit: " + sha + "\n\n"
for args in (["status", "--base-dir", "./t3-other"], ["up", "--base-dir", "./t3-other", "--no-lan"], ["status", "--base-dir", "./t3-other"]):
    result = subprocess.run(["node", str(checkout.resolve() / "apps/server/dist/bin.mjs"), *args], cwd=run, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=120)
    text += "$ t3 " + " ".join(args) + "\n" + result.stdout + "[exit " + str(result.returncode) + "]\n\n"
(root / (str(label) + ".txt")).write_text(text)
print(text)
