//! End-to-end Dockerfile build on KVM: parse a Dockerfile, build each layer by
//! executing it in a microVM and live-snapshotting the result, then boot the
//! final image and confirm the RUN effects are present.

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn main() {
    use std::time::{Duration, Instant};
    use supermachine::{builder, Image, VmConfig};

    // The apk RUN exercises build-time networking (TSI egress + DNS + correct
    // guest clock for TLS) — it must SUCCEED (no `|| true`), so a network/clock
    // regression fails the build instead of silently shipping without jq.
    let dockerfile = "FROM alpine\n\
        RUN echo built-by-kvm > /built\n\
        RUN mkdir -p /app && echo v1 > /app/version\n\
        RUN apk add --no-cache jq\n";
    let df = builder::parse(dockerfile).expect("parse");
    eprintln!("=== parsed {} stage(s) ===", df.stages.len());

    let ctx = std::env::temp_dir().join("sm-build-ctx");
    let _ = std::fs::create_dir_all(&ctx);
    let dest = "/tmp/sm-built-image";
    let _ = std::fs::remove_dir_all(dest);

    let base = Image::from_oci("alpine").expect("from_oci base");
    eprintln!("=== build_linear (layer-per-snapshot on KVM) ===");
    let t0 = Instant::now();
    let out = builder::build_linear(&df, &base, &ctx, dest).expect("build_linear");
    eprintln!("build took {:?}", t0.elapsed());

    eprintln!("=== boot final image, verify RUN effects ===");
    let vm = out.image.start(&VmConfig::new()).expect("start built");
    std::thread::sleep(Duration::from_millis(5000));
    let o = vm
        .exec_builder()
        .argv([
            "/bin/sh",
            "-c",
            "cat /built; cat /app/version; (command -v jq >/dev/null && echo jq-ok || echo jq-missing)",
        ])
        .output()
        .expect("exec verify");
    let got = String::from_utf8_lossy(&o.stdout).trim_end().to_string();
    eprintln!("built image contents:\n{got}");
    vm.stop().ok();

    let pass = got.contains("built-by-kvm") && got.contains("v1") && got.contains("jq-ok");
    eprintln!(
        "=== KVM DOCKERFILE BUILD: {} ===",
        if pass { "PASS" } else { "FAIL" }
    );
}

#[cfg(not(all(target_os = "linux", target_arch = "x86_64")))]
fn main() {
    eprintln!("kvm_build is Linux/x86_64 only");
}
