//! Diagnose stage_file. Stages a file, then in a SEPARATE exec
//! lists /tmp to see if it landed.

use std::time::Duration;
use supermachine::Image;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let snap = format!(
        "{}/.local/supermachine-snapshots/rust_1_slim",
        std::env::var("HOME")?
    );
    let image = Image::from_snapshot(&snap)?;
    // Use restore_on_release(false) so state survives between
    // execs and we can introspect.
    let pool = image
        .pool()
        .min(1)
        .max(1)
        .idle_timeout(Duration::MAX)
        .restore_on_release(false)
        .build()?;
    let vm = pool.acquire()?;

    // First exec: stage_file + ls
    println!("=== exec1: stage_file + ls /tmp ===");
    let out = vm
        .exec_builder()
        .stage_file("/tmp/probe.txt", b"hello-stage".to_vec())
        .argv(["ls", "-la", "/tmp"].iter().copied())
        .timeout(Duration::from_secs(10))
        .output()?;
    println!("status={} stderr={:?}", out.status, String::from_utf8_lossy(&out.stderr));
    println!("stdout:\n{}", String::from_utf8_lossy(&out.stdout));

    // Second exec: just cat the staged file
    println!("=== exec2: cat /tmp/probe.txt ===");
    let out = vm
        .exec_builder()
        .argv(["cat", "/tmp/probe.txt"].iter().copied())
        .timeout(Duration::from_secs(10))
        .output()?;
    println!("status={} stderr={:?}", out.status, String::from_utf8_lossy(&out.stderr));
    println!("stdout:\n{}", String::from_utf8_lossy(&out.stdout));

    // Third exec: same exec1 but with a NEW stage_file path,
    // followed by an ls in the same exec via chain.
    println!("=== exec3: stage_file + ls in same call ===");
    let out = vm
        .exec_builder()
        .stage_file("/tmp/probe2.txt", b"second-stage".to_vec())
        .argv(["cat", "/tmp/probe2.txt"].iter().copied())
        .timeout(Duration::from_secs(10))
        .output()?;
    println!("status={} stderr={:?}", out.status, String::from_utf8_lossy(&out.stderr));
    println!("stdout:\n{}", String::from_utf8_lossy(&out.stdout));
    Ok(())
}
