#![deny(missing_docs)]
// SPDX-FileCopyrightText: Peter Pentchev <roam@ringlet.net>
// SPDX-License-Identifier: BSD-2-Clause
//! Generate the POSIX shell test suite for remrun.
//!
//! Read the JSON test definitions and convert them to a POSIX shell program.

use std::fs;

use anyhow::{Context as _, Result};
use itertools::Itertools as _;
use tracing::debug;

mod builder;
mod cli;
mod defs;
mod loader;

fn main() -> Result<()> {
    let cfg = cli::parse_args().context("Could not parse the command-line options")?;
    debug!("starting up");
    let test_defs = loader::load_defs().context("Could not load the test definitions")?;
    debug!("loaded {count} tests", count = test_defs.tests().len());
    debug!(
        "{defs}",
        defs = test_defs
            .tests()
            .iter()
            .map(|tdef| format!("- {title}", title = tdef.title()))
            .join("\n")
    );

    let contents =
        builder::generate(&test_defs).context("Could not generate the test file's contents")?;
    debug!(
        "Writing {count} bytes of output to {output_file}",
        count = contents.len(),
        output_file = cfg.output_file()
    );

    fs::write(cfg.output_file(), &contents).with_context(|| {
        format!(
            "Could not write {count} bytes to {output_file}",
            count = contents.len(),
            output_file = cfg.output_file()
        )
    })?;
    Ok(())
}
