//! The `cloud-init` sub-command.

use crate::cloudinit::{CloudInitConfig, CloudInitError};
use crate::progress::Progress;
use crate::spec::Specification;
use std::path::Path;

/// Errors from this module.
#[derive(Debug, thiserror::Error)]
pub enum CloudInitCommandError {
    /// Error in the cloud-init configuration.
    #[error(transparent)]
    CloudInitError(#[from] CloudInitError),

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

/// The `cloud-init` sub-command.
///
/// This sub-command generates the cloud-init configuration based on
/// specifications provided by the caller and writes them to files in
/// a directory named by the caller.
pub fn cloud_init(
    specs: &[Specification],
    progress: &Progress,
    dirname: &Path,
) -> Result<(), CloudInitCommandError> {
    for spec in specs {
        let dirname = dirname.join(&spec.name);
        progress.chatty(&format!(
            "generating cloud-init configuration for {} into {}",
            spec.name,
            dirname.display()
        ));

        let init = CloudInitConfig::from(spec)?;

        progress.chatty(&format!("creating directory {}", dirname.display()));
        std::fs::create_dir_all(&dirname)?;
        init.create_dir(&dirname)?;
    }

    Ok(())
}
