#!/usr/bin/env python3
"""Boot Omarchy ISO with serial, then start the installer by hand from the root shell."""
import os
import subprocess
import time

import pexpect

HERE = os.path.dirname(os.path.abspath(__file__))
ISO = os.path.join(HERE, "omarchy-4.5.0-x86.iso")
DISK = os.path.join(HERE, "omarchy-disk.qcow2")
CIDATA = os.path.join(HERE, "cidata.img")

uuid = subprocess.run(["sudo", "blkid", "-p", "-s", "UUID", "-o", "value", ISO],
                      capture_output=True, text=True, check=True).stdout.strip()
qemu = [
    "qemu-system-x86_64", "-name", "omarchy-manual-install", "-m", "4096", "-smp", "4",
    "-machine", "pc", "-display", "none", "-serial", "stdio", "-monitor", "none",
    "-kernel", "/mnt/omarchy-iso/arch/boot/x86_64/vmlinuz-linux-omarchy",
    "-initrd", "/mnt/omarchy-iso/arch/boot/x86_64/initramfs-linux-omarchy.img",
    "-append", (f"archisobasedir=arch archisosearchuuid={uuid} copytoram=n "
                "initramfs_options=size=90% console=ttyS0,115200 systemd.show_status=0"),
    "-drive", f"file={ISO},media=cdrom,readonly=on,if=ide",
    "-drive", f"file={DISK},if=virtio,format=qcow2",
    "-drive", f"file={CIDATA},if=virtio,format=raw,readonly=on",
    "-netdev", "user,id=n1,hostfwd=tcp::2222-:22",
    "-device", "virtio-net-pci,netdev=n1",
]
log = open(os.path.join(HERE, "omarchy-manual-install.serial"), "w", errors="replace")
child = pexpect.spawn(qemu[0], qemu[1:], timeout=600, encoding="utf-8", codec_errors="replace",
                      logfile=log)
child.delaybeforesend = 0.05
child.expect(r"login:\s*$", timeout=600)
child.sendline("root")
idx = child.expect([r"[Pp]assword:\s*", r"archiso[^\n]*[#$]", pexpect.TIMEOUT], timeout=60)
if idx == 0:
    child.sendline("")
child.expect(r"archiso[^\n]*[#$]", timeout=180)

setup = [
    "export OMARCHY_PATH=/usr/share/omarchy OMARCHY_INSTALL=/usr/share/omarchy/install",
    "export OMARCHY_INSTALL_LOG_FILE=/var/log/omarchy-install.log",
    "export OMARCHY_MIRROR=$(cat /root/omarchy_mirror 2>/dev/null || echo https://mirror.omarchy.org)",
    "echo READY_TO_INSTALL",
]
for c in setup:
    child.sendline(c)
    time.sleep(0.4)

cmd = ("/usr/local/bin/omarchy-iso-install "
       "--config /root/user_configuration.json "
       "--creds /root/user_credentials.json "
       "--authorized-keys-file /root/authorized_keys")
child.sendline(cmd)
print("installer started on serial console; logging to omarchy-manual-install.serial", flush=True)
try:
    # "Installation complete." is printed only after every phase, including
    # finalize_boot_and_user (Limine ESP/UKI), has finished.
    child.expect(r"Installation complete\.", timeout=5400)
    print("installer reported true completion; settling", flush=True)
    time.sleep(60)
except pexpect.TIMEOUT:
    print("installer still running after 90 min", flush=True)
child.close(force=True)
