use crate::log;
use std::{fmt::Display, future::Future, process::ExitCode};
use tokio::{select, signal::ctrl_c};

/// This is inner main function wrapper.
///
/// It sets up logging, runs the provided `main` future or returns on Ctrl-C.
#[inline]
pub async fn run_main<E: Display>(main: impl Future<Output = Result<(), E>>) -> ExitCode {
	log::setup_log(&log::Config::default());
	select! {
		_ = ctrl_c() => {
			eprintln!("Ctrl-C received");
			ExitCode::FAILURE
		}
		result = main => match result {
			Ok(()) => ExitCode::SUCCESS,
			Err(e) => {
				eprintln!("{e}");
				ExitCode::FAILURE
			},
		}
	}
}
