//! DAX step 1 validation: boot a VM on the experimental virtio-fs/FUSE/DAX
//! kernel (via SUPERMACHINE_KVM_KERNEL) and confirm the guest has FUSE +
//! virtio-fs + DAX support built in. Proves the kernel config (step 1 of
//! docs/design/kvm-virtiofs-dax-2026-06-07.md) before any device-side work.
//!
//! Usage:
//!   SUPERMACHINE_KVM_KERNEL=/root/linux-6.12.30/arch/x86/boot/bzImage \
//!     cargo run --example kvm_dax_kernel_probe

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

    if std::env::var_os("SUPERMACHINE_KVM_KERNEL").is_none() {
        eprintln!("set SUPERMACHINE_KVM_KERNEL=/path/to/dax-bzImage first");
        std::process::exit(2);
    }
    let dest = std::env::temp_dir().join("sm-dax-probe-img");
    let _ = std::fs::remove_dir_all(&dest);
    // bake_kvm_auto honors SUPERMACHINE_KVM_KERNEL (copies it instead of the
    // bundled kernel), so this boots alpine on the experimental kernel.
    let image = Image::bake_kvm_auto("alpine", &dest).expect("bake_kvm_auto");
    let vm = image.start(&VmConfig::new()).expect("start");
    std::thread::sleep(Duration::from_millis(4000));

    let o = vm
        .exec_builder()
        .argv([
            "/bin/sh",
            "-c",
            "echo '== filesystems =='; cat /proc/filesystems | grep -E 'fuse|virtiofs' || echo none; \
             echo '== virtio-fs module/builtin =='; (ls -d /sys/bus/virtio/drivers/virtio_fs 2>/dev/null && echo virtio_fs-driver-present) || echo no-virtio_fs-driver; \
             echo '== dax =='; (ls /sys/class/dax 2>/dev/null; grep -i dax /proc/filesystems) || echo no-dax-class; \
             echo '== kver =='; uname -r",
        ])
        .output()
        .expect("probe exec");
    let out = String::from_utf8_lossy(&o.stdout);
    eprintln!("--- guest probe ---\n{out}");
    vm.stop().ok();

    let fuse = out.contains("fuse");
    let vfs = out.contains("virtio_fs-driver-present") || out.contains("virtiofs");
    eprintln!(
        "=== DAX KERNEL PROBE: fuse={} virtio_fs={} ===\n{}",
        fuse,
        vfs,
        if fuse && vfs {
            "PASS (kernel has FUSE + virtio-fs; proceed to the device step)"
        } else {
            "FAIL (config didn't stick — inspect .config)"
        }
    );
}

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