#!/bin/bash
# Shared, safe package-management helpers for onix-base commands.
set -u

ONIX_PACMAN=/usr/bin/pacman
ONIX_SYSTEM_FIX=/usr/bin/onix-system-fix
ONIX_REFLECTOR=/usr/bin/reflector

as_root() {
    if (( EUID == 0 )); then
        "$@"
    elif command -v sudo >/dev/null 2>&1; then
        sudo "$@"
    else
        echo "onix: root privileges or sudo are required" >&2
        return 1
    fi
}

run_repair() {
    [[ -x "$ONIX_SYSTEM_FIX" ]] || return 0
    # onix-system-fix is the compatibility entry point for onix-configure;
    # its supported system-repair mode is --repair.  The former apply mode was
    # never valid and made every updater/opkg transaction fail immediately.
    as_root "$ONIX_SYSTEM_FIX" --repair
}

refresh_mirrors() {
    [[ -x "$ONIX_REFLECTOR" ]] || {
        echo "onix: reflector is not installed; keeping the current mirrorlist"
        return 0
    }
    [[ -d /etc/pacman.d ]] || return 0

    # Create the temporary file as root in the destination directory.  Some
    # reflector versions open the --save path after dropping privileges; a
    # user-owned file in /tmp can therefore fail with "Permission denied".
    local temp_mirrorlist
    temp_mirrorlist=$(as_root mktemp /etc/pacman.d/.onix-mirrorlist.XXXXXX) || return 1
    if ! as_root "$ONIX_REFLECTOR" --latest 20 --sort rate --save "$temp_mirrorlist"; then
        as_root rm -f -- "$temp_mirrorlist"
        echo "onix: reflector failed; keeping the current mirrorlist" >&2
        return 1
    fi
    if ! as_root install -m 0644 "$temp_mirrorlist" /etc/pacman.d/mirrorlist; then
        as_root rm -f -- "$temp_mirrorlist"
        return 1
    fi
    as_root rm -f -- "$temp_mirrorlist"
    echo "onix: mirrorlist updated"
}

prepare_keyring() {
    [[ -x /usr/bin/pacman-key ]] || return 0
    as_root /usr/bin/pacman-key --init
    as_root /usr/bin/pacman-key --populate archlinux
}

full_upgrade() {
    run_repair || return 1
    prepare_keyring || return 1
    # A full upgrade is intentional here. Never split -Sy from -Su.
    as_root "$ONIX_PACMAN" -Syu --noconfirm "$@"
}

install_packages() {
    [[ "$#" -gt 0 ]] || {
        echo "onix: at least one package is required" >&2
        return 2
    }
    full_upgrade --needed "$@"
}

remove_packages() {
    [[ "$#" -gt 0 ]] || {
        echo "onix: at least one package is required" >&2
        return 2
    }
    run_repair || return 1
    as_root "$ONIX_PACMAN" -Rns --noconfirm "$@"
}

clean_cache() {
    run_repair || return 1
    as_root "$ONIX_PACMAN" -Sc --noconfirm
}
