//! Bake-and-run from a registry image reference, end-to-end.
//!
//! ```sh
//! cargo install supermachine                       # CLI + plugin
//! cargo supermachine build --release --example oci_simple
//! target/release/examples/oci_simple nginx:1.27-alpine
//! ```

use std::io::{Read, Write};
use std::time::Instant;

use supermachine::{Image, PullPolicy, Vm, VmConfig};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let image_ref = std::env::args()
        .nth(1)
        .unwrap_or_else(|| "nginx:1.27-alpine".to_owned());

    let t0 = Instant::now();
    // PullPolicy::Missing: cache-first. Pulls + bakes only if no
    // valid local snapshot exists.
    let image = Image::from_oci_with_policy(&image_ref, PullPolicy::Missing)?;
    eprintln!("image ready in {:?}", t0.elapsed());

    let t1 = Instant::now();
    let vm = Vm::start(&image, &VmConfig::new())?;
    eprintln!("vm started in {:?}", t1.elapsed());

    let mut sock = vm.connect()?;
    sock.write_all(
        b"GET / HTTP/1.1\r\nHost: workload\r\nConnection: close\r\n\r\n",
    )?;
    let mut response = Vec::new();
    sock.read_to_end(&mut response)?;
    let preview = String::from_utf8_lossy(&response);
    for line in preview.lines().take(4) {
        eprintln!("  {line}");
    }

    vm.stop()?;
    eprintln!("done in {:?}", t0.elapsed());
    Ok(())
}
