#!/usr/bin/env python3
"""Install instantOS from its live ISO into a target qcow2 disk, unattended."""
import argparse
import json
import os
import subprocess
import sys
import time

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from boot_vm import iso_boot_assets  # noqa: E402

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

QUESTIONS = """[answers]
Disk = "/dev/vda"
PartitioningMethod = "automatic"
UseEncryption = "no"
Hostname = "instantos-bench"
Username = "instantos"
Password = "instantos"
Keymap = "us"
Timezone = "UTC"
Locale = "en_US.UTF-8"
"""


def ssh_args(port):
    return ["sshpass", "-p", "instantos", "ssh",
            "-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=/dev/null",
            "-o", "ConnectTimeout=10", "-o", "PreferredAuthentications=password",
            "-p", str(port), "instantos@127.0.0.1"]


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--iso", required=True)
    p.add_argument("--disk", required=True)
    p.add_argument("--ram", type=int, default=4096)
    p.add_argument("--smp", type=int, default=4)
    p.add_argument("--port", type=int, default=2226)
    p.add_argument("--timeout", type=int, default=7200)
    args = p.parse_args()

    kpath, ipath, uuid = iso_boot_assets(args.iso, "install-instantos")
    serial = os.path.join(HERE, "install-instantos.serial")
    qemu = [
        "qemu-system-x86_64", "-name", "install-instantos", "-m", str(args.ram),
        "-smp", str(args.smp), "-display", "none", "-vga", "virtio",
        "-serial", f"file:{serial}", "-monitor", "none", "-no-reboot",
        "-machine", "pc",
        "-kernel", kpath, "-initrd", ipath,
        "-append", (f"console=ttyS0,115200 systemd.show_status=1 "
                    f"archisobasedir=instos archisosearchuuid={uuid}"),
        "-drive", f"file={args.iso},media=cdrom,readonly=on,if=ide",
        "-drive", f"file={args.disk},if=virtio,format=qcow2",
        "-netdev", f"user,id=n1,hostfwd=tcp::{args.port}-:22",
        "-device", "virtio-net-pci,netdev=n1",
    ]
    result = {"qemu": " ".join(qemu), "start": time.time()}
    proc = subprocess.Popen(qemu, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    try:
        deadline = time.time() + 900
        while time.time() < deadline:
            if subprocess.run(ssh_args(args.port) + ["true"], capture_output=True).returncode == 0:
                break
            time.sleep(10)
        else:
            raise RuntimeError("SSH never became ready")
        result["ssh_ready_s"] = round(time.time() - result["start"], 1)

        # write questions.toml
        r = subprocess.run(ssh_args(args.port) + ["cat > /root/questions.toml"],
                           input=QUESTIONS, text=True, capture_output=True)
        if r.returncode != 0:
            raise RuntimeError(f"writing questions failed: {r.stderr}")

        check = subprocess.run(
            ssh_args(args.port) + ["sudo -n ins arch check --target -f /root/questions.toml"],
            capture_output=True, text=True, timeout=300)
        result["check_rc"] = check.returncode
        result["check_output"] = check.stdout[-8000:] + check.stderr[-4000:]
        if check.returncode != 0:
            raise RuntimeError("ins arch check failed")

        install = subprocess.run(
            ssh_args(args.port) + ["sudo -n ins arch exec -f /root/questions.toml"],
            capture_output=True, text=True, timeout=args.timeout)
        result["install_rc"] = install.returncode
        result["install_output"] = (install.stdout[-12000:] + install.stderr[-6000:])
    except Exception as e:
        result["error"] = repr(e)
    finally:
        proc.kill()
        proc.wait()
        result["duration_s"] = round(time.time() - result["start"], 1)

    with open(os.path.join(HERE, "install-instantos.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))
    for key in ("check_output", "install_output"):
        if result.get(key):
            print(f"=== {key} ===")
            print(result[key])


if __name__ == "__main__":
    main()
