#!/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

# --- 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 -r -p "$1 [y/N] " response
    [[ "$response" =~ ^[yY]$ ]]
}

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

# --- Prerequisites ---

if [[ $EUID -eq 0 ]]; then
    err "Do NOT run as root. The script uses sudo where needed."
    exit 1
fi

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

log "=== Update system packages ==="

if confirm "Run pacman -Syu?"; then
    sudo pacman -Syu
else
    log "System update skipped."
fi

if command -v paru &>/dev/null; then
    if confirm "Update AUR packages (paru -Sua)?"; then
        paru -Sua
    else
        log "AUR update skipped."
    fi
fi

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

log "=== Reconcile package lists ==="

if [[ -f "$OFFICIAL_PACKAGES" ]]; then
    MISSING_OFFICIAL=$(comm -23 <(read_packages "$OFFICIAL_PACKAGES" | sort) <(pacman -Qq | sort) || true)
    if [[ -n "$MISSING_OFFICIAL" ]]; then
        log "Missing official packages:"
        echo "$MISSING_OFFICIAL"
        if confirm "Install?"; then
            # shellcheck disable=SC2086
            sudo pacman -S --needed --noconfirm $MISSING_OFFICIAL
        fi
    else
        log "All official packages installed."
    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 "Missing AUR packages:"
        echo "$MISSING_AUR"
        if confirm "Install?"; then
            # shellcheck disable=SC2086
            paru -S --needed --noconfirm $MISSING_AUR
        fi
    else
        log "All AUR packages installed."
    fi
fi

# --- 3. Orphaned packages ---

log "=== Orphaned packages ==="

ORPHANS=$(pacman -Qdtq 2>/dev/null || true)
if [[ -n "$ORPHANS" ]]; then
    log "Orphaned packages found:"
    echo "$ORPHANS"
    if confirm "Remove?"; then
        # shellcheck disable=SC2086
        sudo pacman -Rsn --noconfirm $ORPHANS
    fi
else
    log "No orphaned packages."
fi

# --- Done ---

log ""
log "============================================"
log "  Moonarch update complete!"
log "============================================"
