use std::process::Command;

fn main() {
    if !has_bun() {
        install_bun();
    }
    run_install();
}

fn has_bun() -> bool {
    Command::new("bun")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

fn install_bun() {
    #[cfg(target_os = "windows")]
    {
        println!("Installing bun on Windows...");
        let output = Command::new("powershell")
            .args(["-NoProfile", "-Command", "irm bun.sh | iex"])
            .output()
            .expect("Failed to install bun");
        if !output.status.success() {
            eprintln!("{}", String::from_utf8_lossy(&output.stderr));
            std::process::exit(1);
        }
    }
    #[cfg(not(target_os = "windows"))]
    {
        println!("Installing bun...");
        let output = Command::new("sh")
            .args(["-c", "curl -fsSL https://bun.sh/install | bash"])
            .output()
            .expect("Failed to install bun");
        if !output.status.success() {
            eprintln!("{}", String::from_utf8_lossy(&output.stderr));
            std::process::exit(1);
        }
    }
}

fn run_install() {
    let script = include_str!("../install.sh");
    Command::new("sh")
        .args(["-c", &script])
        .env("SKIP_NGINX", "true")
        .spawn()
        .expect("Failed to run install script")
        .wait()
        .expect("Install script failed");
}