#!/usr/bin/env bash

util::cmdExists()            { command -v "$1" &>/dev/null; }
util::isAptInstalled()       { dpkg -l "$1" 2>/dev/null | grep -q "^ii"; }
util::isSnapInstalled()      { snap list "$1" &>/dev/null 2>&1; }
util::isFlatpakInstalled()   { flatpak list --app --columns=application 2>/dev/null | grep -q "^$1$"; }
util::isYamlNull()           { [[ -z "$1" || "$1" == "null" ]]; }

util::confirm() {
    local question="${1:-¿Continuar?} [s/N] "
    local answer
    read -rp "$question" answer
    [[ "${answer,,}" == "s" || "${answer,,}" == "si" || "${answer,,}" == "sí" ]]
}

util::keepSudoAlive() {
    while true; do
        sudo -n true
        sleep 50
        kill -0 "$$" || exit
    done 2>/dev/null &
}

util::requireSudo() {
    [[ "$EUID" -eq 0 ]] && return
    if ! sudo -n true 2>/dev/null; then
        log::info "Se requieren permisos de administrador"
        sudo -v
    fi
    util::keepSudoAlive
}

util::aptUpdateOnce() {
    if [[ "${aptUpdated:-false}" != "true" ]]; then
        log::info "Actualizando índices de apt..."
        sudo apt-get update -qq
        aptUpdated=true
        export aptUpdated
    fi
}
