//! Validate that KVM snapshots carry data-volume ATTACHMENTS (SMSNAP04): boot a
//! VM with a volume mounted at /data, write a probe, take a LIVE snapshot, then
//! restore it with a bare `VmConfig::new()` (NO volume re-declared) and confirm
//! the volume is still attached + mounted and the probe reads back. This proves
//! the snapshot records the mapping (path/size/mount + device state); the
//! contents live in the host backing file, referenced by path.

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

    let dir = "/tmp/sm-vol-snap";
    let backing = "/tmp/sm-vol-snap.img";
    let _ = std::fs::remove_dir_all(dir);
    let _ = std::fs::remove_file(backing);

    let cfg = VmConfig::new().with_volume(VolumeSpec {
        host_path: backing.to_string(),
        guest_path: "/data".to_string(),
        size_bytes: 64 * 1024 * 1024,
    });

    let image = Image::from_oci("alpine").expect("from_oci");

    eprintln!("=== VM #1: mount /data (vol), write a probe, live-snapshot ===");
    let vm = image.start(&cfg).expect("start1");
    std::thread::sleep(Duration::from_millis(5000));
    let w = vm
        .exec_builder()
        .argv([
            "/bin/sh",
            "-c",
            "mount | grep -q ' /data ' && V=vol-snap-$(date +%s) && echo $V > /data/probe && sync && cat /data/probe",
        ])
        .output()
        .expect("exec write");
    let written = String::from_utf8_lossy(&w.stdout).trim_end().to_string();
    eprintln!("VM#1: success={} probe={:?}", w.success(), written);

    let snap = vm.snapshot_live(dir).expect("snapshot_live");
    vm.stop().expect("stop1");

    eprintln!("=== VM #2: restore with BARE VmConfig (no volume re-declared) ===");
    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",
            "M=$(mount | grep -c ' /data '); P=$(cat /data/probe 2>/dev/null); echo mounted=$M probe=$P",
        ])
        .output()
        .expect("restore exec");
    let got = String::from_utf8_lossy(&r.stdout).trim_end().to_string();
    eprintln!("restored: success={} {got:?}", r.success());
    vm2.stop().ok();

    let pass = w.success()
        && r.success()
        && got.contains("mounted=1")
        && got.contains(&format!("probe={written}"));
    eprintln!(
        "=== VOLUME-IN-SNAPSHOT: {} ===",
        if pass { "PASS" } else { "FAIL" }
    );
}

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