haj 0.3.6

the beautiful, cross-distro package manager and tui.
#[cfg(feature = "pacman")]
pub mod alpm_init;
pub mod aur;
#[cfg(feature = "pacman")]
pub mod conflicts;
pub mod downgrade;
pub mod package;
pub mod pacman;
pub mod process;
pub mod ui;

#[allow(unused_imports)]
use anyhow::Result;
use crossterm::style::Stylize;
use std::process::Stdio;
use tokio::process::Command;

pub const PRIVILEGE_CANDIDATES: &[&str] = &["sudo", "doas", "run0", "pkexec"];

fn parse_euid_from_proc_status(status: &str) -> Option<u32> {
    status
        .lines()
        .find_map(|line| line.strip_prefix("Uid:"))
        .and_then(|rest| rest.split_whitespace().nth(1))
        .and_then(|euid| euid.parse::<u32>().ok())
}

pub fn is_root() -> bool {
    std::fs::read_to_string("/proc/self/status")
        .ok()
        .and_then(|s| parse_euid_from_proc_status(&s))
        .is_some_and(|euid| euid == 0)
}

pub fn binary_in_path(bin: &str) -> bool {
    let path = std::path::Path::new(bin);
    if path.is_absolute() || bin.contains('/') {
        return path.is_file();
    }
    std::env::var_os("PATH")
        .is_some_and(|paths| std::env::split_paths(&paths).any(|dir| dir.join(bin).is_file()))
}

pub fn select_privilege_cmd(
    env_override: Option<&str>,
    configured: Option<&str>,
    has_bin: impl Fn(&str) -> bool,
) -> String {
    fn explicit(opt: Option<&str>) -> Option<&str> {
        opt.map(str::trim)
            .filter(|s| !s.is_empty() && !s.eq_ignore_ascii_case("auto"))
    }
    if let Some(cmd) = explicit(env_override) {
        return cmd.to_string();
    }
    if let Some(cmd) = explicit(configured) {
        return cmd.to_string();
    }
    PRIVILEGE_CANDIDATES
        .iter()
        .find(|&&c| has_bin(c))
        .copied()
        .unwrap_or("sudo")
        .to_string()
}

/// Resolves privilege escalation command (`HAJ_PRIVILEGE_CMD` -> config -> PATH fallback).
pub fn resolve_privilege_cmd() -> String {
    let env_val = std::env::var("HAJ_PRIVILEGE_CMD").ok();
    let cfg = crate::config::load_config();
    select_privilege_cmd(
        env_val.as_deref(),
        cfg.general.privilege_cmd.as_deref(),
        binary_in_path,
    )
}

pub fn priv_bin_name(cmd: &str) -> &str {
    std::path::Path::new(cmd)
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or(cmd)
}

/// Builds `(program, args)` to execute `executable args...`, escalating when not root.
pub fn build_privileged_invocation(
    priv_cmd: &str,
    executable: &str,
    args: &[String],
    env: &[(String, String)],
) -> (String, Vec<String>) {
    if is_root() {
        return (executable.to_string(), args.to_vec());
    }
    let mut final_args = Vec::with_capacity(args.len() + env.len() + 2);
    if !env.is_empty() {
        // `sudo` supports inline `K=V`; `doas`/`run0`/`pkexec` need `env K=V`.
        if priv_bin_name(priv_cmd) != "sudo" {
            final_args.push("env".to_string());
        }
        for (k, v) in env {
            final_args.push(format!("{k}={v}"));
        }
    }
    final_args.push(executable.to_string());
    final_args.extend(args.iter().cloned());
    (priv_cmd.to_string(), final_args)
}

pub fn format_dry_run_prefix(requires_root: bool) -> String {
    if !requires_root || is_root() {
        String::new()
    } else {
        format!("{} ", resolve_privilege_cmd())
    }
}

fn priv_needs_tty_ticket(priv_cmd: &str) -> bool {
    matches!(priv_bin_name(priv_cmd), "sudo" | "doas")
}

pub async fn has_cached_privilege_ticket() -> bool {
    if is_root() {
        return true;
    }
    let priv_cmd = resolve_privilege_cmd();
    match priv_bin_name(&priv_cmd) {
        "sudo" => Command::new(&priv_cmd)
            .args(["-n", "-v"])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .await
            .is_ok_and(|s| s.success()),
        "doas" => Command::new(&priv_cmd)
            .args(["-n", "true"])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .await
            .is_ok_and(|s| s.success()),
        // `run0` / `pkexec` prompt at invocation via polkit (no cached TTY ticket).
        _ => true,
    }
}

pub async fn refresh_privilege_ticket() {
    let _ = has_cached_privilege_ticket().await;
}

pub async fn ensure_sudo() -> anyhow::Result<()> {
    if has_cached_privilege_ticket().await {
        return Ok(());
    }

    let priv_cmd = resolve_privilege_cmd();
    if priv_needs_tty_ticket(&priv_cmd) {
        let auth_arg = if priv_bin_name(&priv_cmd) == "sudo" {
            "-v"
        } else {
            "true"
        };
        println!("{} haj demands elevated privileges.", "::".blue().bold());
        let auth = Command::new(&priv_cmd).arg(auth_arg).status().await?;
        if !auth.success() {
            anyhow::bail!("authentication failed or aborted.");
        }
    }

    Ok(())
}

#[cfg(test)]
mod privilege_tests {
    use super::*;

    #[test]
    fn test_select_privilege_cmd_priority() {
        assert_eq!(
            select_privilege_cmd(Some("doas"), Some("run0"), |_| true),
            "doas"
        );
        assert_eq!(select_privilege_cmd(None, Some("run0"), |_| true), "run0");
        assert_eq!(
            select_privilege_cmd(Some("   "), None, |bin| bin == "doas"),
            "doas"
        );
        assert_eq!(
            select_privilege_cmd(None, None, |bin| bin == "pkexec"),
            "pkexec"
        );
        assert_eq!(
            select_privilege_cmd(None, Some("auto"), |bin| bin == "doas"),
            "doas"
        );
        assert_eq!(
            select_privilege_cmd(Some(" AUTO "), Some("sudo"), |bin| bin == "doas"),
            "sudo"
        );
        assert_eq!(select_privilege_cmd(None, None, |_| false), "sudo");
    }

    #[test]
    fn test_build_privileged_invocation_env_handling() {
        if is_root() {
            return;
        }
        let args = vec!["install".into(), "-y".into(), "htop".into()];
        let env = vec![("LC_ALL".into(), "C.UTF-8".into())];

        let (prog_sudo, args_sudo) = build_privileged_invocation("sudo", "apt-get", &args, &env);
        assert_eq!(prog_sudo, "sudo");
        assert_eq!(
            args_sudo,
            vec!["LC_ALL=C.UTF-8", "apt-get", "install", "-y", "htop"]
        );

        let (prog_doas, args_doas) =
            build_privileged_invocation("/usr/bin/doas", "apt-get", &args, &env);
        assert_eq!(prog_doas, "/usr/bin/doas");
        assert_eq!(
            args_doas,
            vec!["env", "LC_ALL=C.UTF-8", "apt-get", "install", "-y", "htop"]
        );
    }

    #[test]
    fn test_priv_needs_tty_ticket() {
        assert!(priv_needs_tty_ticket("sudo"));
        assert!(priv_needs_tty_ticket("/usr/bin/doas"));
        assert!(!priv_needs_tty_ticket("run0"));
        assert!(!priv_needs_tty_ticket("pkexec"));
    }

    #[test]
    fn test_parse_euid_from_proc_status() {
        assert_eq!(
            parse_euid_from_proc_status("Name:\thaj\nUid:\t1000\t1000\t1000\t1000\n"),
            Some(1000)
        );
        assert_eq!(
            parse_euid_from_proc_status("Name:\thaj\nUid:\t1000\t0\t0\t0\n"),
            Some(0)
        );
        assert_eq!(parse_euid_from_proc_status("Name:\thaj\n"), None);
    }
}