//! Bake the warm rustc snapshot used by axis_bench.

use std::time::Duration;
use supermachine::{Image, VmConfig};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let snap = format!(
        "{}/.local/supermachine-snapshots/rust_1_slim",
        std::env::var("HOME")?
    );
    let dest = format!(
        "{}/.local/supermachine-snapshots/rust_1_slim__warm__rustc_v1",
        std::env::var("HOME")?
    );
    if std::path::Path::new(&dest).is_dir() {
        println!("warm snapshot already exists, skipping");
        return Ok(());
    }
    let base = Image::from_snapshot(&snap)?;
    let pooled = base.acquire_with(&VmConfig::new())?;
    println!("warming...");
    let _ = pooled
        .exec_builder()
        .stage_file(
            "/tmp/main.rs",
            b"fn main() { println!(\"hello\"); }".to_vec(),
        )
        .argv(["rustc", "-O", "/tmp/main.rs", "-o", "/tmp/m"].iter().copied())
        .chain(["/tmp/m"].iter().copied())
        .timeout(Duration::from_secs(60))
        .output()?;
    println!("snapshotting...");
    let _ = pooled.snapshot(&dest)?;
    println!("baked at {dest}");
    Ok(())
}
