//! The `start` sub-command.

use crate::libvirt::{Libvirt, VirtError};
use crate::progress::Progress;
use crate::spec::Specification;
use crate::util::wait_for_ssh;

/// Errors from this module.
#[derive(Debug, thiserror::Error)]
pub enum StartError {
    /// Error from libvirt.
    #[error(transparent)]
    VirtError(#[from] VirtError),

    /// Error doing I/O.
    #[error(transparent)]
    IoError(#[from] std::io::Error),
}

/// Start existing VMs corresponding to specifications.
pub fn start(specs: &[Specification], progress: &Progress) -> Result<(), StartError> {
    progress.chatty("starting virtual machines");

    let libvirt = Libvirt::connect("qemu:///system")?;
    for spec in specs {
        progress.step(&format!("starting virtual machine {}", spec.name));
        libvirt.trigger_start(&spec.name)?;
    }
    for spec in specs {
        wait_for_ssh(&spec.name);
    }

    progress.chatty("started OK");
    Ok(())
}
