#!/bin/bash
# ABOUTME: Moonarch system updater — updates packages and reconciles package lists.
# ABOUTME: Shipped as /usr/bin/moonarch-update by the moonarch-git package.

set -euo pipefail

_t() {
    # _t "english" "deutsch" — picks by $LANG
    case "${LANG%%.*}" in
        de_*) printf '%s' "$2" ;;
        *)    printf '%s' "$1" ;;
    esac
}

# Pause on exit when launched from a GUI (Waybar sets MOONUP_WAIT=1).
# Runs via trap so it fires even when `set -e` aborts the script mid-way.
# Reads from /dev/tty because stdin may have been drained/closed by pacman/paru.
_pause_on_exit() {
    local rc=$?
    if [[ -n "${MOONUP_WAIT:-}" ]]; then
        echo
        if (( rc != 0 )); then
            echo -e "\e[1;31m[Moonarch ERROR]\e[0m $(_t "Exited with error (code $rc)" "Mit Fehler beendet (Code $rc)")" >&2
        fi
        read -n 1 -s -r -p "$(_t "Press any key to close..." "Beliebige Taste drücken zum Schließen …")" < /dev/tty || true
        echo
    fi
}
trap _pause_on_exit EXIT

# --- i18n ---
# Reuse pacman's gettext catalog for prompts that match upstream msgids.
# For moonarch-specific strings fall back to _t() inline translation.
export TEXTDOMAIN=pacman
export TEXTDOMAINDIR=/usr/share/locale
YN=$(gettext "[Y/n]")

# --- Helper functions ---

log() {
    echo -e "\e[1;34m[Moonarch]\e[0m $*"
}

err() {
    echo -e "\e[1;31m[Moonarch ERROR]\e[0m $*" >&2
}

read_packages() {
    grep -v '^\s*#' "$1" | grep -v '^\s*$'
}

confirm() {
    # Read from /dev/tty so stdin state (drained by pacman/paru, closed by
    # a Waybar launch) doesn't auto-confirm prompts by returning empty input.
    read -r -p ":: $1 $YN " response < /dev/tty
    [[ -z "$response" || "$response" =~ ^[yYjJ]$ ]]
}

OFFICIAL_PACKAGES="/usr/share/moonarch/official.txt"
AUR_PACKAGES="/usr/share/moonarch/aur.txt"

# --- Prerequisites ---

if [[ $EUID -eq 0 ]]; then
    err "$(_t "Do NOT run as root. The script uses sudo where needed." "Nicht als root ausführen. Das Script verwendet sudo wo nötig.")"
    exit 1
fi

# --- 1. Update system packages ---

log "=== $(gettext $'Starting full system upgrade...\n' | tr -d '\n.') ==="

if confirm "$(_t "Run pacman -Syu?" "pacman -Syu ausführen?")"; then
    sudo pacman -Syu
else
    log "$(_t "System update skipped." "Systemaktualisierung übersprungen.")"
fi

if command -v paru &>/dev/null; then
    if confirm "$(_t "Update AUR packages (paru -Sua)?" "AUR-Pakete aktualisieren (paru -Sua)?")"; then
        paru -Sua
    else
        log "$(_t "AUR update skipped." "AUR-Aktualisierung übersprungen.")"
    fi
fi

# --- 2. Reconcile package lists ---

log "=== $(_t "Reconcile package lists" "Paketlisten abgleichen") ==="

if [[ -f "$OFFICIAL_PACKAGES" ]]; then
    MISSING_OFFICIAL=$(comm -23 <(read_packages "$OFFICIAL_PACKAGES" | sort) <(pacman -Qq | sort) || true)
    if [[ -n "$MISSING_OFFICIAL" ]]; then
        log "$(_t "Missing official packages:" "Fehlende offizielle Pakete:")"
        echo "$MISSING_OFFICIAL"
        if confirm "$(gettext 'Proceed with installation?')"; then
            # shellcheck disable=SC2086
            sudo pacman -S --needed --noconfirm $MISSING_OFFICIAL
        fi
    else
        log "$(_t "All official packages installed." "Alle offiziellen Pakete installiert.")"
    fi
fi

if [[ -f "$AUR_PACKAGES" ]] && command -v paru &>/dev/null; then
    MISSING_AUR=$(comm -23 <(read_packages "$AUR_PACKAGES" | sort) <(pacman -Qq | sort) || true)
    if [[ -n "$MISSING_AUR" ]]; then
        log "$(_t "Missing AUR packages:" "Fehlende AUR-Pakete:")"
        echo "$MISSING_AUR"
        if confirm "$(gettext 'Proceed with installation?')"; then
            # shellcheck disable=SC2086
            paru -S --needed --noconfirm $MISSING_AUR
        fi
    else
        log "$(_t "All AUR packages installed." "Alle AUR-Pakete installiert.")"
    fi
fi

# --- 3. Orphaned packages ---

log "=== $(_t "Orphaned packages" "Verwaiste Pakete") ==="

ORPHANS=$(pacman -Qdtq 2>/dev/null || true)
if [[ -n "$ORPHANS" ]]; then
    log "$(_t "Orphaned packages found:" "Verwaiste Pakete gefunden:")"
    echo "$ORPHANS"
    if confirm "$(gettext 'Do you want to remove these packages?')"; then
        # shellcheck disable=SC2086
        sudo pacman -Rsn --noconfirm $ORPHANS
    fi
else
    log "$(_t "No orphaned packages." "Keine verwaisten Pakete.")"
fi

# --- Done ---

log ""
log "============================================"
log "  $(_t "Moonarch update complete!" "Moonarch-Aktualisierung abgeschlossen!")"
log "============================================"
