#!/usr/bin/env python3
"""Boot installed instantOS directly, log in on serial, and probe idle memory."""
import argparse
import json
import os
import re
import time

import pexpect

HERE = os.path.dirname(os.path.abspath(__file__))


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--disk", default=os.path.join(HERE, "instantos-target.qcow2"))
    p.add_argument("--ram", type=int, required=True)
    p.add_argument("--smp", type=int, default=4)
    p.add_argument("--tag", required=True)
    p.add_argument("--settle", type=int, default=180)
    p.add_argument("--probe-timeout", type=int, default=240)
    p.add_argument("--probe", required=True)
    p.add_argument("--pre-probe", default="", help="command run after login, before settling")
    args = p.parse_args()

    cmdline = ("root=UUID=970f8ee8-8338-484a-b286-22ce7fd0e3bf rw rootflags=subvol=@ "
               "console=ttyS0,115200 systemd.show_status=1")
    qemu = [
        "qemu-system-x86_64", "-name", args.tag, "-m", str(args.ram), "-smp", str(args.smp),
        "-display", "none", "-vga", "virtio", "-serial", "stdio",
        "-monitor", "none", "-no-reboot", "-machine", "pc",
        "-kernel", os.path.join(HERE, "boot", "inst-vmlinuz"),
        "-initrd", os.path.join(HERE, "boot", "inst-initramfs.img"),
        "-append", cmdline,
        "-drive", f"file={args.disk},if=virtio,format=qcow2",
        "-netdev", "user,id=n1", "-device", "virtio-net-pci,netdev=n1",
    ]
    result = {"tag": args.tag, "ram_mib": args.ram, "qemu": " ".join(qemu), "start": time.time()}
    log = open(os.path.join(HERE, f"{args.tag}.serial"), "w", errors="replace")
    child = pexpect.spawn(qemu[0], qemu[1:], timeout=600, logfile=log,
                          encoding="utf-8", codec_errors="replace")
    child.delaybeforesend = 0.05
    try:
        child.expect(r"login:\s*$", timeout=600)
        result["login_s"] = round(time.time() - result["start"], 1)
        child.sendline("instantos")
        idx = child.expect([r"[Pp]assword:\s*", r"login:\s*$", pexpect.TIMEOUT], timeout=30)
        result["password_prompt"] = idx == 0
        if idx == 0:
            child.sendline("instantos")
        child.sendline("id")
        ok = child.expect([r"uid=\d+\(instantos\)", r"login:\s*$", pexpect.TIMEOUT], timeout=120)
        result["shell"] = ok == 0
        if ok != 0:
            raise RuntimeError("could not get a user shell")
        if args.pre_probe:
            child.sendline(f"{args.pre_probe}; echo __PRE_DONE__")
            child.expect(r"(?m)^__PRE_DONE__\s*$", timeout=120)
            result["pre_probe"] = args.pre_probe
        time.sleep(args.settle)
        child.sendline(args.probe.replace("\n", "; "))
        child.expect(r"(?m)^### PROBE_DONE\s*$", timeout=args.probe_timeout)
        result["probe_output"] = re.sub(r"\x1b\[[0-9;?]*[a-zA-Z]", "", child.before)[-20000:]
    except Exception as e:
        result["error"] = repr(e)
    finally:
        try:
            child.close(force=True)
        except Exception:
            pass
        result["duration_s"] = round(time.time() - result["start"], 1)

    with open(os.path.join(HERE, f"{args.tag}.json"), "w") as f:
        json.dump(result, f, indent=2)
    print(json.dumps({k: v for k, v in result.items() if "output" not in k}, indent=2))
    if result.get("probe_output"):
        print("=== PROBE OUTPUT ===")
        print(result["probe_output"])


if __name__ == "__main__":
    main()
