1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
//! ### IQPS Backend
//!
//! The backend is divided into multiple modules. The [`routing`] module contains all the route handlers and the [`db`] module contains all database queries and models. Other modules are utilities used throughout the backend.

use clap::Parser;
use tracing_subscriber::prelude::*;

mod auth;
mod db;
mod env;
mod pathutils;
mod qp;
mod routing;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Read dotenv if it exists
    if dotenvy::dotenv().is_ok() {
        println!("Loaded an existing .env file.");
    }

    // Read environment variables
    let env_vars = env::EnvVars::parse().process()?;

    // Initialize logger
    let (append_writer, _guard) = tracing_appender::non_blocking(tracing_appender::rolling::never(
        env_vars
            .log_location
            .parent()
            .expect("Where do you want to store that log??"),
        env_vars
            .log_location
            .file_name()
            .expect("Do you want to store the logs in a directory?"),
    ));

    let subscriber = tracing_subscriber::registry()
        .with(
            tracing_subscriber::fmt::layer()
                .with_writer(append_writer)
                .with_ansi(false),
        )
        .with(tracing_subscriber::fmt::layer().with_writer(std::io::stdout));

    tracing::subscriber::set_global_default(subscriber)?;

    // Database connection
    let database = db::Database::new(&env_vars).await?;

    // Server
    let listener =
        tokio::net::TcpListener::bind(format!("0.0.0.0:{}", env_vars.server_port)).await?;
    tracing::info!("Starting server on port {}", env_vars.server_port);
    axum::serve(listener, routing::get_router(&env_vars, database)).await?;

    Ok(())
}