use std::time::Duration;

use supermachine::internal::{
    vmm::pool::WarmPool,
    RunOptions,
    VmResources,
};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut args = std::env::args().skip(1);
    let snapshot = args.next().ok_or(
        "usage: cargo run -p supermachine --example warm_pool -- SNAPSHOT [ITERATIONS]",
    )?;
    let iterations = args
        .next()
        .map(|s| s.parse::<usize>())
        .transpose()?
        .unwrap_or(1);

    let resources = VmResources::from_snapshot(&snapshot).with_cow_restore(true);
    let pool = WarmPool::start(resources, RunOptions::default())?;

    for i in 0..iterations {
        let restored = pool.restore_timeout(&snapshot, Duration::from_secs(5))?;
        println!(
            "restore={} restore_us={} host_port={:?}",
            i + 1,
            restored.restore_us,
            restored.host_port
        );
    }

    let report = pool.shutdown()?;
    println!("warm_restores={}", report.warm_restores);
    Ok(())
}
