//! Validate NON-consuming (live) KVM snapshots: snapshot a running VM, keep
//! using it afterward, and confirm a restore of the live snapshot reflects the
//! state at capture time (changes made AFTER capture are absent).

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

    let dir = "/tmp/sm-live-snap";
    let _ = std::fs::remove_dir_all(dir);

    let image = Image::from_oci("alpine").expect("from_oci");
    let vm = image.start(&VmConfig::new()).expect("start");
    std::thread::sleep(Duration::from_millis(5000));

    vm.exec_builder()
        .argv(["/bin/sh", "-c", "echo A > /root/a"])
        .output()
        .expect("write a");

    eprintln!("=== live snapshot (non-consuming) ===");
    let snap = vm.snapshot_live(dir).expect("snapshot_live");

    let after = vm
        .exec_builder()
        .argv(["/bin/sh", "-c", "echo B > /root/b && cat /root/a /root/b"])
        .output()
        .expect("post-snap exec");
    eprintln!(
        "post-snapshot exec (VM still live): success={} out={:?}",
        after.success(),
        String::from_utf8_lossy(&after.stdout)
            .trim_end()
            .replace('\n', ",")
    );
    vm.stop().expect("stop");

    eprintln!("=== restore the live snapshot ===");
    let vm2 = snap.start(&VmConfig::new()).expect("restore start");
    std::thread::sleep(Duration::from_millis(3000));
    let r = vm2
        .exec_builder()
        .argv([
            "/bin/sh",
            "-c",
            "echo a=$(cat /root/a 2>/dev/null) b=$(cat /root/b 2>/dev/null)",
        ])
        .output()
        .expect("restore exec");
    let got = String::from_utf8_lossy(&r.stdout).trim_end().to_string();
    eprintln!("restored state: {got:?}");
    vm2.stop().ok();

    let pass = after.success() && got.contains("a=A") && got.contains("b=") && !got.contains("b=B");
    eprintln!(
        "=== LIVE SNAPSHOT: {} ===",
        if pass { "PASS" } else { "FAIL" }
    );
}

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