pub mod bake;
mod download;
pub mod env;
pub mod files;
mod git;
mod qemu;
mod seed;
pub mod ssh;

use crate::app::bus::{Bus, Event};
use std::path::Path;
use std::process::{Child, Stdio};
use std::time::{Duration, Instant};

pub enum Vm {
    Off,
    Booting,
    Ready(u16),
    Failed(String),
}

impl Vm {
    pub fn port(&self) -> Option<u16> {
        match self {
            Vm::Ready(p) => Some(*p),
            _ => None,
        }
    }
}

pub struct Machine(Child);

impl Drop for Machine {
    fn drop(&mut self) {
        let _ = self.0.kill();
        let _ = self.0.wait();
    }
}

pub fn boot(bus: &Bus, dir: &Path, state: &Path) -> std::io::Result<Machine> {
    std::fs::create_dir_all(state)?;
    let port = std::net::TcpListener::bind("127.0.0.1:0")?
        .local_addr()?
        .port();
    let child = qemu::command(
        &files::disk(),
        &[("work", dir, false), ("cast", state, false)],
    )
    .arg("-snapshot")
    .arg("-nic")
    .arg(format!(
        "user,model=virtio-net-pci,hostfwd=tcp:127.0.0.1:{port}-:22"
    ))
    .arg("-serial")
    .arg(format!("file:{}", files::console_log().display()))
    .stdin(Stdio::null())
    .stdout(Stdio::null())
    .stderr(Stdio::null())
    .spawn()?;
    let bus = bus.clone();
    let identity = git::identity();
    std::thread::spawn(move || {
        let start = Instant::now();
        while start.elapsed() < Duration::from_secs(180) {
            if ssh::run(
                port,
                "mountpoint -q /work && mountpoint -q /cast && DISPLAY=:0 xset q",
            ) {
                ssh::run(port, &identity);
                return bus.send(Event::Vm(Ok(port)));
            }
            std::thread::sleep(Duration::from_secs(2));
        }
        bus.send(Event::Vm(Err(
            "the VM did not come up with its mounts and desktop within 3 minutes".into(),
        )));
    });
    Ok(Machine(child))
}
