use crate::vm::files;
use std::io::Write;
use std::process::{Child, Command, Stdio};

pub fn spawn(port: u16, script: &str) -> std::io::Result<Child> {
    let mut child = Command::new("ssh")
        .args(["-i"])
        .arg(files::key())
        .args(["-p", &port.to_string()])
        .args([
            "-o",
            "StrictHostKeyChecking=no",
            "-o",
            "UserKnownHostsFile=/dev/null",
        ])
        .args([
            "-o",
            "LogLevel=ERROR",
            "-o",
            "BatchMode=yes",
            "-o",
            "ConnectTimeout=5",
        ])
        .args(["cast@127.0.0.1", "bash", "-s"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()?;
    child
        .stdin
        .take()
        .map(|mut s| s.write_all(script.as_bytes()));
    Ok(child)
}

pub fn quote(s: &str) -> String {
    format!("'{}'", s.replace('\'', "'\\''"))
}

pub fn run(port: u16, script: &str) -> bool {
    spawn(port, script)
        .and_then(|c| c.wait_with_output())
        .is_ok_and(|o| o.status.success())
}

#[cfg(test)]
mod tests {
    #[test]
    fn quote_survives_single_quotes() {
        assert_eq!(super::quote("O'Neil"), r"'O'\''Neil'");
    }
}
