use dope_aws::creds::Credentials;
use dope_aws::ops::{cloudformation, rds};
use dope_aws::region::Region;

fn main() {
    let creds = Credentials::new(
        env("AWS_ACCESS_KEY_ID"),
        env("AWS_SECRET_ACCESS_KEY"),
        std::env::var("AWS_SESSION_TOKEN").ok(),
    );
    let region =
        Region::new(std::env::var("AWS_REGION").unwrap_or_else(|_| "ap-southeast-1".to_string()));

    let mut args = std::env::args().skip(1);
    let cmd = args.next().unwrap_or_default();
    let arg = args.next().unwrap_or_default();

    let result = match cmd.as_str() {
        "describe-stacks" => cloudformation::describe_stacks(&creds, &region, &arg).map(|outs| {
            outs.iter()
                .map(|o| format!("  {} = {}", o.key, o.value))
                .collect::<Vec<_>>()
                .join("\n")
        }),
        "describe-db" => rds::db_instance_endpoint(&creds, &region, &arg),
        other => {
            eprintln!("unknown command: {other:?} (expected describe-stacks | describe-db)");
            std::process::exit(2);
        }
    };

    match result {
        Ok(out) => println!("ok:\n{out}"),
        Err(e) => {
            eprintln!("error: {e}");
            std::process::exit(1);
        }
    }
}

fn env(key: &str) -> String {
    std::env::var(key).unwrap_or_else(|_| {
        eprintln!("missing env var {key}");
        std::process::exit(2);
    })
}
