#![warn(rust_2018_idioms)]

#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;

#[macro_use]
extern crate slog_scope;

mod auth;
mod error;
mod extractors;
mod headers;
mod metrics;
mod routers;
mod routes;
mod server;
mod settings;

use docopt::Docopt;
use serde::Deserialize;
use std::error::Error;

use autopush_common::logging;

const USAGE: &str = "
Usage: autoendpoint [options]

Options:
    -h, --help                  Show this message
    -c, --config=CONFIGFILE     AutoEndpoint configuration file path.
";

#[derive(Debug, Deserialize)]
struct Args {
    flag_config: Option<String>,
}

#[actix_rt::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Must run before any TLS use: reqwest (outbound HTTPS to push services)
    // builds its rustls config via the default provider and panics if none is
    // installed when multiple providers are compiled in; tonic/bigtable adopts
    // whatever we install here.
    autopush_common::tls::install_crypto_provider();
    let args: Args = Docopt::new(USAGE)
        .and_then(|d| d.deserialize())
        .unwrap_or_else(|e| e.exit());
    let settings = settings::Settings::with_env_and_config_file(&args.flag_config)?;
    let host_port = format!("{}:{}", &settings.host, &settings.port);
    logging::init_logging(
        !settings.human_logs,
        env!("CARGO_PKG_NAME"),
        env!("CARGO_PKG_VERSION"),
    )
    .expect("Logging failed to initialize");
    debug!("Starting up autoendpoint...");

    let _sentry = sentry::init(sentry::ClientOptions {
        release: sentry::release_name!(),
        attach_stacktrace: true,
        ..autopush_common::sentry::client_options()
    });

    // Run server...
    let server = server::Server::with_settings(settings)
        .await
        .inspect_err(|e| error!("Server Start Error: {:?}", e))
        .expect("Could not start server");
    info!(
        "Starting autoendpoint on port: {} ({})",
        host_port,
        logging::parallelism_banner()
    );
    server.await?;

    // Shutdown
    info!("Shutting down autoendpoint");
    logging::reset_logging();
    Ok(())
}
