//! Diagnose package-install-over-network in a guest (apk add). Distinguishes
//! network/DNS failure from cert/repo issues, to tell if a builder RUN that
//! installs packages is a supermachine bug or image content (e.g. ca-certs).

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

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

    for (label, cmd) in [
        ("resolv.conf", "cat /etc/resolv.conf"),
        ("ca-certs?", "ls -la /etc/ssl/certs/ca-certificates.crt 2>&1 | head -1"),
        ("dns lookup", "nslookup dl-cdn.alpinelinux.org 2>&1 | tail -3 || getent hosts dl-cdn.alpinelinux.org 2>&1"),
        ("apk update", "apk update 2>&1 | tail -4"),
        ("apk add jq", "apk add --no-cache jq 2>&1 | tail -6; echo RC=$?"),
        ("jq present?", "command -v jq && jq --version 2>&1"),
    ] {
        let o = vm
            .exec_builder()
            .argv(["/bin/sh", "-c", cmd])
            .output()
            .expect("exec");
        eprintln!(
            "--- {label} ---\n{}",
            String::from_utf8_lossy(&o.stdout).trim_end()
        );
    }
    vm.stop().ok();
}

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