use std::path::Path;

use ambient_ci::{action::Context, plan::RunnablePlan, runlog::RunLog};

const PLAN_FILENAME: &str = "plan.yaml";

fn main() {
    let mut runlog = RunLog::default();
    runlog.stdout();
    let mut context = Context::new(&mut runlog);
    if let Err(err) = fallible_main(&mut context) {
        eprintln!("ERROR: {err}");
        let mut source = err.source();
        while let Some(src) = source {
            eprintln!("caused by: {src}");
            source = src.source();
        }
        context.runlog().executor_ends_in_failure(1);
        std::process::exit(1);
    }
}

fn fallible_main(context: &mut Context) -> Result<(), Box<dyn std::error::Error>> {
    let name = "ambient-execute-plan";
    let version = env!("VERSION");

    context.runlog().executor_starts(name, version);
    context.set_env("HOME", "/root");

    let plan = RunnablePlan::from_file(Path::new(PLAN_FILENAME))?;
    context.runlog().runnable_plan(&plan);
    context.set_envs_from_plan(&plan)?;
    plan.execute(context)?;

    context.runlog().executor_ends_successfully();

    Ok(())
}
