//! This binary is a minimal implementation of the Server module of this crate's library.
//!
//! Configure the server with a `toe-beans.toml` file.
//!
//! This binary is only built if the `v4_server` feature is enabled.
//! The `v4_server` feature is enabled by default.

use clap::Parser;
use std::path::PathBuf;
use toe_beans::v4::{
    init_logger,
    server::{Server, ServerConfig},
};
use tracing::{debug, info};

#[derive(Parser, Debug)]
struct Cli {
    /// The path where all config files are stored.
    /// Must be a directory that exists on disk.
    /// Defaults to empty which resolves downstream to the current directory.
    #[arg(long)]
    config: Option<PathBuf>,
}

fn main() {
    let maybe_guard = init_logger(false);
    let _guard = maybe_guard.unwrap(); // always Some if non-blocking
    info!(
        "Starting toe-beans server (version {})",
        env!("CARGO_PKG_VERSION")
    );

    let parsed = Cli::parse();
    let config_path: PathBuf = match parsed.config {
        Some(path) => {
            if !path.is_dir() {
                panic!("The --config arg must be a path to an existing directory");
            }
            path
        }
        None => PathBuf::new(),
    };
    debug!("Config path is {:?}", config_path);
    let config = ServerConfig::read(config_path);

    let mut server = Server::new(config);
    server.listen()
}
