use std::str::FromStr;

use log::LevelFilter;

pub mod base64;
pub mod bitwarden;
pub mod curl;
pub mod env;
pub mod fs;
pub mod json;
pub mod proc;
pub mod yaml;

pub fn read_level_filter() -> LevelFilter {
    let env = env::read_env("LOGLEVEL").unwrap_or(String::from("INFO"));
    let env_upper = env.to_uppercase();
    let level = match env_upper.as_str() {
        "VERBOSE" => "TRACE",
        "WARNING" => "WARN",
        l => l,
    };
    log::LevelFilter::from_str(level).unwrap_or(log::LevelFilter::Info)
}

pub fn entrypoint(m: impl FnOnce() -> anyhow::Result<()>) {
    env_logger::builder()
        .filter_level(read_level_filter())
        .format_timestamp(None)
        .format_module_path(false)
        .format_file(false)
        .format_source_path(false)
        .format_target(false)
        .try_init()
        .expect("Could not set logger");
    let res = m();
    if let Err(err) = res {
        log::error!("{err:#}");
        std::process::exit(1);
    }
}
