// SPDX-FileCopyrightText: 2026 Contributors to brew-proxy <https://codeberg.org/HastD/brew-proxy>
//
// SPDX-License-Identifier: Apache-2.0 OR MIT

use std::{fs, process::ExitCode, time::Duration};

use nix::unistd::{Uid, User};
use tracing::error;
use tracing_subscriber::EnvFilter;

use brew_proxy::daemon;
use brew_proxy_utils::{BREW_EXECUTABLE, BREW_PREFIX, BREW_USER, BusType};

const IDLE_TIMEOUT: Duration = Duration::from_secs(300);

#[tokio::main]
async fn main() -> ExitCode {
    let subscriber = tracing_subscriber::fmt().with_env_filter(EnvFilter::from_default_env());
    // Disable timestamps by default since in the usual scenario, messages will
    // be logged to the system journal, which already records timestamps.
    match std::env::var("RUST_LOG_TIME").as_deref() {
        Ok("") | Ok("0") | Ok("false") | Err(_) => subscriber.without_time().init(),
        _ => subscriber.init(),
    }

    if !matches!(fs::exists(BREW_EXECUTABLE), Ok(true)) {
        error!("Homebrew installation not detected at {BREW_PREFIX}");
        return ExitCode::FAILURE;
    }

    match User::from_uid(Uid::effective()) {
        Ok(Some(user)) if user.name == BREW_USER => {}
        Ok(Some(_)) => {
            error!("brew-proxy-daemon must be run as the '{BREW_USER}' user");
            return ExitCode::FAILURE;
        }
        Ok(None) | Err(_) => {
            error!("Unable to get current username. Exiting.");
            return ExitCode::FAILURE;
        }
    }

    if let Err(err) = daemon::run_with_idle_timeout(
        BREW_EXECUTABLE.into(),
        BusType::System,
        Box::new(daemon::PolkitAuth),
        IDLE_TIMEOUT,
    )
    .await
    {
        error!("{err}");
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    }
}
