//! Binary entry point. Parses CLI arguments, initialises global configuration,
//! builds the CSS theme, constructs the axum router, and starts the HTTP server.

mod cli;

use clap::Parser;
use temp_name::config;
use temp_name::theme::{BASE_CSS, MARKDOWN_CSS};
use temp_name::{error, routes};

#[tokio::main]
async fn main() -> error::Result<()> {
    let args = cli::Args::parse();

    config::set_hostname(args.hostname);
    config::set_ssh_prefix(args.ssh_prefix);
    config::set_base_url(args.base_url);

    let favicon_data = args.favicon.map_or_else(
        || include_bytes!("../static/favicon.svg").to_vec(),
        |path| std::fs::read(&path).unwrap_or_default(),
    );
    config::set_favicon(favicon_data);

    let theme_vars = match args.theme_file {
        Some(path) => std::fs::read_to_string(path)?,
        None => args.theme.css().to_owned(),
    };
    let css = format!("{theme_vars}\n{BASE_CSS}\n{MARKDOWN_CSS}");

    let state = routes::AppState {
        root: args.root,
        css,
    };
    let router = routes::router(state);
    let addr = format!("{}:{}", args.bind, args.port);

    let socket = tokio::net::TcpListener::bind(&addr).await?;
    axum::serve(socket, router).await?;

    Ok(())
}
