use std::io;
use std::path::{Path, PathBuf};
use std::process::Command;

pub fn write(dir: &Path, pubkey: &str, uid: u32) -> io::Result<PathBuf> {
    let src = dir.join("seed");
    std::fs::create_dir_all(&src)?;
    std::fs::write(
        src.join("meta-data"),
        "instance-id: cast-bake\nlocal-hostname: cast\n",
    )?;
    std::fs::write(src.join("user-data"), user_data(pubkey.trim(), uid))?;
    let iso = dir.join("seed.iso");
    let ok = Command::new("xorriso")
        .args([
            "-as", "mkisofs", "-quiet", "-volid", "cidata", "-joliet", "-rock", "-output",
        ])
        .arg(&iso)
        .arg(src.join("user-data"))
        .arg(src.join("meta-data"))
        .status()?
        .success();
    if ok {
        Ok(iso)
    } else {
        Err(io::Error::other(
            "xorriso failed to build the cloud-init seed",
        ))
    }
}

fn user_data(pubkey: &str, uid: u32) -> String {
    format!(
        r#"#cloud-config
users:
  - name: cast
    uid: {uid}
    shell: /bin/bash
    sudo: "ALL=(ALL) NOPASSWD:ALL"
    lock_passwd: true
    ssh_authorized_keys:
      - {pubkey}
ssh_pwauth: false
runcmd:
  - [sh, -c, "mkdir -p /mnt/stage && mount -t 9p -o trans=virtio,version=9p2000.L stage /mnt/stage && bash /mnt/stage/provision.sh; poweroff"]
"#
    )
}
