#!/usr/bin/env python3
"""Boot an ISO (or disk) in QEMU TCG, wait for login, run a probe, report results.

Usage examples:
  ./boot_vm.py --iso /path/live.iso --ram 512 --tag i512 --timeout 420
  ./boot_vm.py --iso /path/live.iso --ram 512 --tag i512 --disk disk.qcow2 \
      --user root --pass '' --login-re 'login:' --expect-cmd 'whoami'
"""
import argparse
import json
import os
import re
import subprocess
import sys
import time

import pexpect

HERE = os.path.dirname(os.path.abspath(__file__))
BOOTDIR = os.path.join(HERE, "boot")
os.makedirs(BOOTDIR, exist_ok=True)


def sh(cmd, **kw):
    return subprocess.run(cmd, shell=True, check=True, capture_output=True, text=True, **kw).stdout.strip()


def iso_boot_assets(iso, tag):
    kpath = os.path.join(BOOTDIR, f"{tag}-vmlinuz")
    ipath = os.path.join(BOOTDIR, f"{tag}-initrd.img")
    if not (os.path.exists(kpath) and os.path.exists(ipath)):
        mnt = f"/mnt/resreq-{tag}"
        sh(f"sudo mkdir -p {mnt}")
        sh(f"sudo mount -o loop,ro {iso} {mnt}")
        try:
            # instantOS uses /instos, Arch/Omarchy use /arch
            candidates = [f"{mnt}/instos/boot/x86_64", f"{mnt}/arch/x86_64", f"{mnt}/arch/boot/x86_64"]
            for d in candidates:
                if os.path.exists(os.path.join(d, "vmlinuz-linux")):
                    sh(f"sudo cp {d}/vmlinuz-linux {kpath}")
                    sh(f"sudo cp {d}/initramfs-linux.img {ipath}")
                    break
            else:
                raise RuntimeError(f"no kernel/initrd found in {iso}; dirs: {candidates}")
        finally:
            sh(f"sudo umount {mnt}")
        sh(f"sudo chmod 644 {kpath} {ipath}")
    uuid = sh(f"sudo blkid -p -s UUID -o value {iso}")
    return kpath, ipath, uuid


def strip_ansi(s):
    s = re.sub(r"\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)", "", s)
    s = re.sub(r"\x1b\[[0-9;?]*[a-zA-Z]", "", s)
    s = re.sub(r"\x1b[()][A-Z0-9]", "", s)
    return s


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--iso", help="ISO to boot from (cdrom)")
    p.add_argument("--disk", help="extra disk image (qcow2/raw), attached as virtio-blk")
    p.add_argument("--ram", type=int, required=True, help="guest RAM in MiB")
    p.add_argument("--tag", required=True)
    p.add_argument("--timeout", type=int, default=600, help="seconds to wait for login")
    p.add_argument("--archiso-dir", default=None, help="archisobasedir, e.g. instos")
    p.add_argument("--append", default="", help="extra kernel cmdline tokens")
    p.add_argument("--no-serial-console", action="store_true",
                   help="don't add console=ttyS0 to the kernel cmdline")
    p.add_argument("--user", default="instantos")
    p.add_argument("--password", default="instantos")
    p.add_argument("--login-re", default=r"login:\s*$")
    p.add_argument("--probe", default="echo __PROBE_OK__", help="shell command run after login")
    p.add_argument("--probe-timeout", type=int, default=180)
    p.add_argument("--settle", type=int, default=0,
                   help="seconds to wait after login before probing (let the desktop settle)")
    p.add_argument("--no-login", action="store_true", help="only wait for login prompt, don't log in")
    p.add_argument("--boot-marker", default=None, help="regex marking successful boot")
    args = p.parse_args()

    serial_log = os.path.join(HERE, f"{args.tag}.serial")
    result_path = os.path.join(HERE, f"{args.tag}.json")

    append_parts = []
    if not args.no_serial_console:
        append_parts += ["console=ttyS0,115200", "systemd.show_status=1"]
    if args.iso:
        kpath, ipath, uuid = iso_boot_assets(args.iso, args.tag)
        append_parts.append(f"archisobasedir={args.archiso_dir or 'instos'}")
        append_parts.append(f"archisosearchuuid={uuid}")
        kernel_args = ["-kernel", kpath, "-initrd", ipath]
        cdrom = ["-drive", f"file={args.iso},media=cdrom,readonly=on,if=ide"]
    else:
        kernel_args = []
        cdrom = []

    cmdline = " ".join(append_parts + [args.append]).strip()
    if cmdline:
        kernel_args += ["-append", cmdline]

    disk_args = []
    if args.disk:
        disk_args = ["-drive", f"file={args.disk},if=virtio,format=qcow2"]

    qemu = [
        "qemu-system-x86_64", "-name", args.tag, "-m", str(args.ram),
        "-smp", "2", "-display", "none", "-serial", "stdio",
        "-monitor", "none", "-no-reboot",
        "-machine", "pc", "-vga", "cirrus",
    ] + kernel_args + cdrom + disk_args

    result = {
        "tag": args.tag, "ram_mib": args.ram, "iso": args.iso, "disk": args.disk,
        "cmdline": cmdline, "qemu": " ".join(qemu), "start": time.time(),
        "booted": False, "login": False, "probe_ok": False,
    }

    with open(serial_log, "w", errors="replace") as log:
        child = pexpect.spawn(qemu[0], qemu[1:], timeout=args.timeout, logfile=log,
                              encoding="utf-8", codec_errors="replace")
        child.delaybeforesend = 0.05
        t0 = time.time()
        try:
            idx = child.expect([args.login_re, "Kernel panic", pexpect.EOF, pexpect.TIMEOUT])
            elapsed = time.time() - t0
            result["login_elapsed_s"] = round(elapsed, 1)
            if idx == 0:
                result["login"] = True
                result["booted"] = True
                if not args.no_login:
                    # Wait for the real Password: prompt (TCG makes NSS slow).
                    child.sendline(args.user)
                    pidx = child.expect(
                        [r"[Pp]assword:\s*", args.login_re, pexpect.TIMEOUT], timeout=90)
                    result["password_prompt"] = pidx == 0
                    if pidx == 0:
                        child.sendline(args.password)
                    elif pidx == 1:
                        # no password requested (autologin-style getty)
                        pass
                    time.sleep(1)
                    # Use output that cannot appear in the echoed command line.
                    child.sendline("id")
                    try:
                        child.expect(r"uid=\d+\(instantos\)", timeout=90)
                        result["shell"] = True
                    except pexpect.TIMEOUT:
                        result["shell"] = False
                    # prevent pager / prompts from eating output
                    child.sendline("export TERM=dumb PAGER=cat SYSTEMD_PAGER=cat")
                    time.sleep(0.3)
                    if args.settle:
                        time.sleep(args.settle)
                    child.sendline(f"{args.probe}; echo __PROBE_RC__=$?")
                    pidx = child.expect([r"__PROBE_RC__=\d+", pexpect.TIMEOUT], timeout=args.probe_timeout)
                    if pidx == 0:
                        result["probe_ok"] = True
                        before = strip_ansi(child.before)
                        result["probe_output"] = before[-12000:]
            elif idx == 1:
                result["error"] = "kernel panic"
            elif idx == 2:
                result["error"] = "qemu exited before login"
            else:
                result["error"] = "timeout waiting for login"
        except pexpect.exceptions.ExceptionPexpect as e:
            result["error"] = repr(e)
        finally:
            try:
                child.close(force=True)
            except Exception:
                pass
            result["end"] = time.time()
            result["duration_s"] = round(result["end"] - result["start"], 1)

    with open(result_path, "w") as f:
        json.dump(result, f, indent=2)
    print(json.dumps({k: v for k, v in result.items() if k != "probe_output"}, indent=2))
    if result.get("probe_output"):
        print("=== PROBE OUTPUT ===")
        print(result["probe_output"])


if __name__ == "__main__":
    main()
