use std::env;
use std::process::{self, Command};

use creddy_cli::{Action, Cli};


fn main() {
    let cli = Cli::parse();
    let res = match cli.action {
        None | Some(Action::Run)=> launch_gui(),
        Some(Action::Get(args)) => creddy_cli::get(args, cli.global_args),
        Some(Action::Exec(args)) => creddy_cli::exec(args, cli.global_args),
        Some(Action::Shortcut(args)) => creddy_cli::invoke_shortcut(args, cli.global_args),
        Some(Action::Docker(cmd)) => creddy_cli::docker_credential_helper(cmd, cli.global_args),
    };

    if let Err(e) = res {
        eprintln!("Error: {e:?}");
        process::exit(1);
    }
}


fn launch_gui() -> anyhow::Result<()>  {
    let mut path = env::current_exe()?;
    path.pop(); // bin dir

    // binaries are colocated in dev, but not in production
    #[cfg(not(debug_assertions))]
    path.pop(); // install dir

    path.push("creddy.exe"); // exe in main install dir (aka gui exe)

    Command::new(path).spawn()?;
    Ok(())
}
