#!/bin/bash

# ======================================================================
# Archivo:       quirinux-update-notifier
# Ruta:          /usr/local/bin/
# Autor:         Charlie Martínez® <cmartinez@quirinux.org>
# Licencia:      https://www.gnu.org/licenses/gpl-2.0.txt
# Propósito:     Avisar de las actualizaciones (sistema/apt, programas nuevos del
#                wardrobe, kernel nuevo y Flatpak) y dejar que el usuario elija
#                qué instalar. Sustituye a gnome-packagekit (gpk-update-viewer),
#                package-update-indicator y software-properties-gtk.
#
#   Al iniciar sesión (--boot, lo lanza /etc/xdg/autostart):
#     UNA sola notificación (notify-send, con el icono quirinux-notify-update.png):
#     "Hay actualizaciones (N)" con un único botón "Revisar", que abre la
#     pantalla de selección. SIEMPRE se avisa al iniciar sesión mientras haya
#     algo pendiente: da igual que el usuario ya lo haya revisado, cerrado la
#     notificación o dejado sin instalar.
#
#   Al abrir quirinux-update (--interactive):
#     abre directamente la pantalla de selección (o dice que el sistema está
#     al día).
#
#   Pantalla de selección: una lista con casillas marcadas (se pueden
#   desmarcar) con nombre, descripción breve y origen (Sistema, Programa nuevo
#   o Flatpak). No se instala nada que no quede marcado. Todo lo que necesita
#   permisos de administrador se aplica con quirinux-update-apply sin pedir
#   contraseña (polkit, org.quirinux.update.apply).
# Distribución:  Quirinux 2.x
# ======================================================================

#
# Copyright (c) 2019-2025 Charlie Martínez, derechos reservados.
# Licencia: https://www.gnu.org/licenses/gpl-2.0.txt
# Usos autorizados y no autorizados de la marca Quirinux:
# Ver https://www.quirinux.org/aviso-legal
#

set -u

# El idioma se lee antes de forzar LC_ALL=C (que solo se usa para analizar
# la salida de apt/dpkg).
_LOC="${LC_ALL:-${LC_MESSAGES:-${LANG:-}}}"
_LANGS="${LANGUAGE:-}"
# LC_ALL original: zenity/yad necesitan el locale real del usuario para mostrar
# textos con acentos (con LC_ALL=C fallan y no abren la ventana).
_ORIG_LC_ALL="${LC_ALL-}"
export LC_ALL=C

# Rutas (las variables QUN_* solo existen para poder probar el script)
SHARE="${QUN_SHARE:-/usr/local/share/quirinux-update}"
LIST_FILE="$SHARE/wardrobe-packages.list"
OS_RELEASE="${QUN_OS_RELEASE:-/etc/os-release}"
SYNC_BIN="${QUN_SYNC:-/usr/local/bin/quirinux-sync}"
SYNC_STATE="${QUN_SYNC_STATE:-/var/lib/quirinux-update/sync.state}"
OMIT_FILE="${QUN_OMITTED:-/var/lib/quirinux-update/omitted.list}"   # paquetes que quirinux-sync no pudo instalar aquí
SYNC_LOG="${QUN_SYNC_LOG:-/var/log/quirinux-update/latest.log}"
STATE_DIR="${QUN_STATE:-${XDG_STATE_HOME:-${HOME:-/tmp}/.local/state}/quirinux/update-notifier}"
LOCK_FILE="${QUN_LOCK:-${XDG_RUNTIME_DIR:-/tmp}/quirinux-update-notifier-$(id -u).lock}"
BOOT_ID=$(cat "${QUN_BOOT_ID:-/proc/sys/kernel/random/boot_id}" 2>/dev/null || echo desconocido)

# Estado (todo por usuario)
DISMISSED_KERNEL="$STATE_DIR/kernel"       # último kernel al que el usuario dijo "No me interesa"
DISMISSED_PKGS="$STATE_DIR/packages"       # programas del wardrobe a los que dijo "No me interesa"
DISMISSED_FP="$STATE_DIR/flatpak"          # líneas "ámbito aplicación commit"
DISMISSED_APT="$STATE_DIR/apt"             # líneas "paquete versión" (actualizaciones del sistema)
APPLY_BIN="${QUN_APPLY:-/usr/lib/quirinux-update/quirinux-update-apply}"
APPLY_LOG="${QUN_APPLY_LOG:-/var/log/quirinux/quirinux-update.log}"
ICON="${QUN_ICON:-/usr/share/pixmaps/quirinux-notify-update.png}"   # lo instala este paquete
[ -r "$ICON" ] || ICON=system-software-update
LATER_BOOT="$STATE_DIR/later-boot"         # identificador del arranque en el que dijo "Revisar más tarde"
REFRESH_STAMP="$STATE_DIR/last-refresh"
ROOT_HELPER="${QUN_ROOT_HELPER:-/usr/lib/quirinux-update/quirinux-update-root}"   # lo ejecuta pkexec (polkit org.quirinux.update.run)
LOG_FILE="$STATE_DIR/notifier.log"

REFRESH_EVERY=120       # segundos mínimos entre "apt-get update" al iniciar sesión (2 min; antes 6 h y ocultaba novedades)
NET_WAIT="${QUN_NET_WAIT:-180}"   # segundos que se espera la red al iniciar sesión

# ----------------------------------------------------------------------
# Opciones
# ----------------------------------------------------------------------
usage() {
    cat <<'EOF'
Uso: quirinux-update-notifier [opciones]

Busca actualizaciones del sistema (apt), programas nuevos del wardrobe de
Quirinux, un kernel nuevo y versiones nuevas de programas de Flathub.

  --boot          (por defecto) al iniciar sesión: una sola notificación
                  "Hay actualizaciones (N)" con el botón Revisar
  --interactive   lo usa quirinux-update: abre directamente la pantalla de
                  selección (o avisa de que el sistema está al día)
  --no-refresh    no actualiza el índice de paquetes antes de comprobar
  --delay N       espera N segundos antes de empezar
  --dry-run, -n   solo dice qué se mostraría; no abre nada ni instala
  --reset         olvida lo desmarcado y los "más tarde" guardados y termina
  -h, --help      esta ayuda
EOF
}

INTERACTIVE=0; REFRESH=1; DELAY=0; DRY=0; RESET=0
while [ $# -gt 0 ]; do
    case "$1" in
        --boot|--autostart) INTERACTIVE=0 ;;
        --interactive)      INTERACTIVE=1 ;;
        --no-refresh)       REFRESH=0 ;;
        --delay)            DELAY="${2:-0}"; shift ;;
        --dry-run|-n)       DRY=1 ;;
        --reset)            RESET=1 ;;
        -h|--help)          usage; exit 0 ;;
        *)                  echo "Opción desconocida: $1" >&2; usage >&2; exit 2 ;;
    esac
    shift
done

if [ "$RESET" -eq 1 ]; then
    rm -f "$DISMISSED_KERNEL" "$DISMISSED_PKGS" "$DISMISSED_FP" "$DISMISSED_APT" "$LATER_BOOT" "$REFRESH_STAMP"
    echo "Respuestas anteriores olvidadas."
    exit 0
fi

mkdir -p "$STATE_DIR" 2>/dev/null
log() {
    [ -w "$STATE_DIR" ] || return 0
    if [ -f "$LOG_FILE" ] && [ "$(stat -c %s "$LOG_FILE" 2>/dev/null || echo 0)" -gt 102400 ]; then
        mv -f "$LOG_FILE" "$LOG_FILE.1" 2>/dev/null
    fi
    printf '%s %s\n' "$(date '+%F %T')" "$*" >> "$LOG_FILE" 2>/dev/null
    [ "$DRY" -eq 1 ] && printf '[notifier] %s\n' "$*" >&2
    return 0
}

# ----------------------------------------------------------------------
# Idioma de los textos
# Mismos idiomas y mismo criterio que el comando "actualizar": es en ru hu de
# it pt fr gl. Se usa el idioma del sistema (LANGUAGE como lista de
# preferencias, y LC_ALL, LC_MESSAGES o LANG); si no está soportado, o el
# locale es C/POSIX, se usa inglés. Se puede forzar con QUN_LANG=xx.
# ----------------------------------------------------------------------
IDIOMAS_SOPORTADOS="es en ru hu de it pt fr gl"

detectar_idioma() {
    local cand l
    local -a lista=()
    if [ -n "${QUN_LANG:-}" ]; then
        lista=("$QUN_LANG")
    else
        case "$_LOC" in
            "" | C | C.* | POSIX | POSIX.*) echo en; return 0 ;;
        esac
        IFS=: read -r -a lista <<< "$_LANGS"
        lista+=("$_LOC")
    fi
    for cand in "${lista[@]}"; do
        l="${cand%%[_.@-]*}"
        l="${l,,}"
        case " $IDIOMAS_SOPORTADOS " in *" $l "*) echo "$l"; return 0 ;; esac
    done
    echo en
}

cargar_textos() {
    case "$1" in
    es)
        L_WORKING_T="Instalando..."
        L_WORKING="Instalando las novedades. Puede tardar varios minutos; no apagues el equipo."
        L_DONE_OK="La instalación ha terminado."
        L_DONE_REBOOT="El kernel nuevo se ha instalado. Reinicia el equipo para empezar a usarlo."
        L_DONE_PART="La instalación ha terminado, pero algunos programas no se han podido instalar. Detalles: %s"
        L_FAIL="No se ha podido completar la instalación. Puedes reintentarlo abriendo Quirinux Update. Detalles: %s"
        L_N_TITLE="ACTUALIZACIONES | Quirinux"
        L_N_BODY="Hay actualizaciones (%s)"
        L_N_KERNEL="Kernel nuevo: %s"
        L_B_REVIEW="Revisar"
        L_W_TITLE="Actualizaciones de Quirinux"
        L_W_TEXT="Desmarca lo que no quieras instalar."
        L_C_NAME="Nombre"
        L_C_DESC="Descripción"
        L_C_ORIGIN="Origen"
        L_T_SYS="Sistema base"
        L_T_KERNEL="Núcleo"
        L_T_QX="Quirinux"
        L_T_NEW="¡Novedad!"
        L_T_FP="Flatpak"
        L_B_INSTALL="Instalar"
        L_B_CANCEL="Cancelar"
        L_FP_SCOPE_SYS="sistema"
        L_FP_SCOPE_USER="usuario"
        L_UPTODATE="El sistema está al día."
        L_NO_NET="No hay conexión a Internet: no se pudo buscar actualizaciones."
        ;;
    gl)
        L_WORKING_T="Instalando..."
        L_WORKING="Instalando as novidades. Pode tardar varios minutos; non apagues o equipo."
        L_DONE_OK="A instalación rematou."
        L_DONE_REBOOT="O kernel novo instalouse. Reinicia o equipo para comezar a usalo."
        L_DONE_PART="A instalación rematou, pero algúns programas non se puideron instalar. Detalles: %s"
        L_FAIL="Non se puido completar a instalación. Podes tentalo de novo abrindo Quirinux Update. Detalles: %s"
        L_N_TITLE="ACTUALIZACIÓNS | Quirinux"
        L_N_BODY="Hai actualizacións (%s)"
        L_N_KERNEL="Kernel novo: %s"
        L_B_REVIEW="Revisar"
        L_W_TITLE="Actualizacións de Quirinux"
        L_W_TEXT="Desmarca o que non queiras instalar."
        L_C_NAME="Nome"
        L_C_DESC="Descrición"
        L_C_ORIGIN="Orixe"
        L_T_SYS="Sistema base"
        L_T_KERNEL="Núcleo"
        L_T_QX="Quirinux"
        L_T_NEW="Novidade!"
        L_T_FP="Flatpak"
        L_B_INSTALL="Instalar"
        L_B_CANCEL="Cancelar"
        L_FP_SCOPE_SYS="sistema"
        L_FP_SCOPE_USER="usuario"
        L_UPTODATE="O sistema está ao día."
        L_NO_NET="Non hai conexión a Internet: non se puideron buscar actualizacións."
        ;;
    fr)
        L_WORKING_T="Installation..."
        L_WORKING="Installation des nouveautés. Cela peut prendre plusieurs minutes ; n'éteignez pas l'ordinateur."
        L_DONE_OK="L'installation est terminée."
        L_DONE_REBOOT="Le nouveau noyau a été installé. Redémarrez l'ordinateur pour l'utiliser."
        L_DONE_PART="L'installation est terminée, mais certains programmes n'ont pas pu être installés. Détails : %s"
        L_FAIL="L'installation n'a pas pu être menée à terme. Vous pouvez réessayer en ouvrant Quirinux Update. Détails : %s"
        L_N_TITLE="MISES À JOUR | Quirinux"
        L_N_BODY="Des mises à jour sont disponibles (%s)"
        L_N_KERNEL="Nouveau noyau : %s"
        L_B_REVIEW="Examiner"
        L_W_TITLE="Mises à jour de Quirinux"
        L_W_TEXT="Décochez ce que vous ne voulez pas installer."
        L_C_NAME="Nom"
        L_C_DESC="Description"
        L_C_ORIGIN="Origine"
        L_T_SYS="Système de base"
        L_T_KERNEL="Noyau"
        L_T_QX="Quirinux"
        L_T_NEW="Nouveauté !"
        L_T_FP="Flatpak"
        L_B_INSTALL="Installer"
        L_B_CANCEL="Annuler"
        L_FP_SCOPE_SYS="système"
        L_FP_SCOPE_USER="utilisateur"
        L_UPTODATE="Votre système est à jour."
        L_NO_NET="Pas de connexion Internet : impossible de rechercher des mises à jour."
        ;;
    de)
        L_WORKING_T="Installation..."
        L_WORKING="Die Neuerungen werden installiert. Das kann einige Minuten dauern; bitte schalten Sie den Computer nicht aus."
        L_DONE_OK="Die Installation ist abgeschlossen."
        L_DONE_REBOOT="Der neue Kernel wurde installiert. Starten Sie den Computer neu, um ihn zu verwenden."
        L_DONE_PART="Die Installation ist abgeschlossen, aber einige Programme konnten nicht installiert werden. Details: %s"
        L_FAIL="Die Installation konnte nicht abgeschlossen werden. Sie können es erneut versuchen, indem Sie Quirinux Update öffnen. Details: %s"
        L_N_TITLE="AKTUALISIERUNGEN | Quirinux"
        L_N_BODY="Aktualisierungen verfügbar (%s)"
        L_N_KERNEL="Neuer Kernel: %s"
        L_B_REVIEW="Ansehen"
        L_W_TITLE="Quirinux-Aktualisierungen"
        L_W_TEXT="Entfernen Sie das Häkchen bei allem, was Sie nicht installieren möchten."
        L_C_NAME="Name"
        L_C_DESC="Beschreibung"
        L_C_ORIGIN="Herkunft"
        L_T_SYS="Basissystem"
        L_T_KERNEL="Kernel"
        L_T_QX="Quirinux"
        L_T_NEW="Neu!"
        L_T_FP="Flatpak"
        L_B_INSTALL="Installieren"
        L_B_CANCEL="Abbrechen"
        L_FP_SCOPE_SYS="System"
        L_FP_SCOPE_USER="Benutzer"
        L_UPTODATE="Ihr System ist auf dem neuesten Stand."
        L_NO_NET="Keine Internetverbindung: Es konnte nicht nach Aktualisierungen gesucht werden."
        ;;
    pt)
        L_WORKING_T="Instalando..."
        L_WORKING="Instalando as novidades. Pode demorar vários minutos; não desligue o computador."
        L_DONE_OK="A instalação foi concluída."
        L_DONE_REBOOT="O novo kernel foi instalado. Reinicie o computador para começar a usá-lo."
        L_DONE_PART="A instalação foi concluída, mas alguns programas não puderam ser instalados. Detalhes: %s"
        L_FAIL="Não foi possível concluir a instalação. Pode tentar novamente abrindo o Quirinux Update. Detalhes: %s"
        L_N_TITLE="ATUALIZAÇÕES | Quirinux"
        L_N_BODY="Há atualizações (%s)"
        L_N_KERNEL="Novo kernel: %s"
        L_B_REVIEW="Revisar"
        L_W_TITLE="Atualizações do Quirinux"
        L_W_TEXT="Desmarque o que não quiser instalar."
        L_C_NAME="Nome"
        L_C_DESC="Descrição"
        L_C_ORIGIN="Origem"
        L_T_SYS="Sistema base"
        L_T_KERNEL="Núcleo"
        L_T_QX="Quirinux"
        L_T_NEW="Novidade!"
        L_T_FP="Flatpak"
        L_B_INSTALL="Instalar"
        L_B_CANCEL="Cancelar"
        L_FP_SCOPE_SYS="sistema"
        L_FP_SCOPE_USER="utilizador"
        L_UPTODATE="O sistema está atualizado."
        L_NO_NET="Sem ligação à Internet: não foi possível procurar atualizações."
        ;;
    it)
        L_WORKING_T="Installazione..."
        L_WORKING="Installazione delle novità in corso. Può richiedere alcuni minuti; non spegnere il computer."
        L_DONE_OK="L'installazione è terminata."
        L_DONE_REBOOT="Il nuovo kernel è stato installato. Riavvia il computer per iniziare a usarlo."
        L_DONE_PART="L'installazione è terminata, ma non è stato possibile installare alcuni programmi. Dettagli: %s"
        L_FAIL="Non è stato possibile completare l'installazione. Puoi riprovare aprendo Quirinux Update. Dettagli: %s"
        L_N_TITLE="AGGIORNAMENTI | Quirinux"
        L_N_BODY="Ci sono aggiornamenti (%s)"
        L_N_KERNEL="Nuovo kernel: %s"
        L_B_REVIEW="Rivedi"
        L_W_TITLE="Aggiornamenti di Quirinux"
        L_W_TEXT="Deseleziona ciò che non vuoi installare."
        L_C_NAME="Nome"
        L_C_DESC="Descrizione"
        L_C_ORIGIN="Origine"
        L_T_SYS="Sistema base"
        L_T_KERNEL="Nucleo"
        L_T_QX="Quirinux"
        L_T_NEW="Novità!"
        L_T_FP="Flatpak"
        L_B_INSTALL="Installa"
        L_B_CANCEL="Annulla"
        L_FP_SCOPE_SYS="sistema"
        L_FP_SCOPE_USER="utente"
        L_UPTODATE="Il sistema è aggiornato."
        L_NO_NET="Nessuna connessione a Internet: impossibile cercare aggiornamenti."
        ;;
    ru)
        L_WORKING_T="Установка..."
        L_WORKING="Идёт установка. Это может занять несколько минут; не выключайте компьютер."
        L_DONE_OK="Установка завершена."
        L_DONE_REBOOT="Новое ядро установлено. Перезагрузите компьютер, чтобы начать его использовать."
        L_DONE_PART="Установка завершена, но некоторые программы установить не удалось. Подробности: %s"
        L_FAIL="Не удалось завершить установку. Попробуйте ещё раз, открыв Quirinux Update. Подробности: %s"
        L_N_TITLE="ОБНОВЛЕНИЯ | Quirinux"
        L_N_BODY="Доступны обновления (%s)"
        L_N_KERNEL="Новое ядро: %s"
        L_B_REVIEW="Просмотреть"
        L_W_TITLE="Обновления Quirinux"
        L_W_TEXT="Снимите отметку с того, что не хотите устанавливать."
        L_C_NAME="Название"
        L_C_DESC="Описание"
        L_C_ORIGIN="Источник"
        L_T_SYS="Базовая система"
        L_T_KERNEL="Ядро"
        L_T_QX="Quirinux"
        L_T_NEW="Новинка!"
        L_T_FP="Flatpak"
        L_B_INSTALL="Установить"
        L_B_CANCEL="Отмена"
        L_FP_SCOPE_SYS="система"
        L_FP_SCOPE_USER="пользователь"
        L_UPTODATE="Система обновлена."
        L_NO_NET="Нет подключения к Интернету: не удалось проверить обновления."
        ;;
    hu)
        L_WORKING_T="Telepítés..."
        L_WORKING="Telepítés folyamatban. Ez eltarthat néhány percig; ne kapcsolja ki a számítógépet."
        L_DONE_OK="A telepítés befejeződött."
        L_DONE_REBOOT="Az új kernel telepítve lett. Indítsa újra a számítógépet a használatához."
        L_DONE_PART="A telepítés befejeződött, de néhány programot nem sikerült telepíteni. Részletek: %s"
        L_FAIL="A telepítést nem sikerült befejezni. Újra megpróbálhatja a Quirinux Update megnyitásával. Részletek: %s"
        L_N_TITLE="FRISSÍTÉSEK | Quirinux"
        L_N_BODY="Frissítések érhetők el (%s)"
        L_N_KERNEL="Új kernel: %s"
        L_B_REVIEW="Áttekintés"
        L_W_TITLE="Quirinux-frissítések"
        L_W_TEXT="Törölje a jelölést azoknál, amiket nem szeretne telepíteni."
        L_C_NAME="Név"
        L_C_DESC="Leírás"
        L_C_ORIGIN="Forrás"
        L_T_SYS="Alaprendszer"
        L_T_KERNEL="Rendszermag"
        L_T_QX="Quirinux"
        L_T_NEW="Újdonság!"
        L_T_FP="Flatpak"
        L_B_INSTALL="Telepítés"
        L_B_CANCEL="Mégse"
        L_FP_SCOPE_SYS="rendszer"
        L_FP_SCOPE_USER="felhasználó"
        L_UPTODATE="A rendszer naprakész."
        L_NO_NET="Nincs internetkapcsolat: a frissítések keresése nem sikerült."
        ;;
    *)
        L_WORKING_T="Installing..."
        L_WORKING="Installing updates. This can take several minutes; please do not turn off the computer."
        L_DONE_OK="The installation has finished."
        L_DONE_REBOOT="The new kernel has been installed. Restart the computer to start using it."
        L_DONE_PART="The installation has finished, but some programs could not be installed. Details: %s"
        L_FAIL="The installation could not be completed. You can try again by opening Quirinux Update. Details: %s"
        L_N_TITLE="UPDATES | Quirinux"
        L_N_BODY="Updates available (%s)"
        L_N_KERNEL="New kernel: %s"
        L_B_REVIEW="Review"
        L_W_TITLE="Quirinux updates"
        L_W_TEXT="Untick anything you do not want to install."
        L_C_NAME="Name"
        L_C_DESC="Description"
        L_C_ORIGIN="Source"
        L_T_SYS="Base system"
        L_T_KERNEL="Kernel"
        L_T_QX="Quirinux"
        L_T_NEW="New!"
        L_T_FP="Flatpak"
        L_B_INSTALL="Install"
        L_B_CANCEL="Cancel"
        L_FP_SCOPE_SYS="system"
        L_FP_SCOPE_USER="user"
        L_UPTODATE="Your system is up to date."
        L_NO_NET="No Internet connection: could not check for updates."
        ;;
    esac
}

L_title="Quirinux Update"
IDIOMA=$(detectar_idioma)
cargar_textos "$IDIOMA"

# ----------------------------------------------------------------------
# Condiciones en las que no se hace nada (en silencio)
# ----------------------------------------------------------------------
log "Inicio (pid $$, modo $([ "$INTERACTIVE" -eq 1 ] && echo interactivo || echo inicio-de-sesión), retardo ${DELAY}s, DISPLAY='${DISPLAY:-}', WAYLAND_DISPLAY='${WAYLAND_DISPLAY:-}')."
[ "$DELAY" -gt 0 ] 2>/dev/null && sleep "$DELAY"

if [ "$DRY" -eq 0 ] && [ -z "${DISPLAY:-}${WAYLAND_DISPLAY:-}" ]; then log "Sin DISPLAY ni WAYLAND_DISPLAY: no se puede avisar."; exit 0; fi
if [ "$(id -u)" -eq 0 ] && [ "$DRY" -eq 0 ]; then log "Se ejecuta como root: el aviso es para el usuario."; exit 0; fi   # es para el usuario, no para root

# Sesión live o chroot (construcción de ISO / instalador): no se toca nada
if grep -qE '(^| )boot=live( |$)' /proc/cmdline 2>/dev/null || [ -d /run/live/medium ]; then log "Sesión live: no se avisa."; exit 0; fi
ischroot 2>/dev/null; [ $? -eq 0 ] && { log "Entorno chroot: no se avisa."; exit 0; }

[ -s "$LIST_FILE" ] || { log "No se encuentra la lista de paquetes: $LIST_FILE"; exit 0; }

ARCH=$(dpkg --print-architecture 2>/dev/null)
CODENAME=$(. "$OS_RELEASE" 2>/dev/null; echo "${VERSION_CODENAME:-}")
case "$ARCH:$CODENAME" in
    amd64:daedalus|amd64:bookworm) ;;
    *) log "Sistema no compatible con el wardrobe ($ARCH:$CODENAME)."; exit 0 ;;
esac
SUITE="${CODENAME}-backports"

# (Antes, tras cerrar la notificación no se volvía a avisar en ese arranque.
# Ahora se avisa en cada inicio de sesión mientras haya actualizaciones.)

# Una sola instancia a la vez. Al iniciar sesión el bloqueo se suelta mientras
# la notificación espera respuesta, para no impedir que quirinux-update abra
# su pantalla.
take_lock() {   # $1 = segundos de espera (0 = no esperar)
    { exec 9>"$LOCK_FILE"; } 2>/dev/null || return 1
    if [ "${1:-0}" -gt 0 ]; then flock -w "$1" 9; else flock -n 9; fi
}
release_lock() { exec 9>&- 2>/dev/null || true; }

if [ "$INTERACTIVE" -eq 1 ]; then take_lock 120 || { log "No se pudo obtener el bloqueo $LOCK_FILE (otra instancia en marcha)."; exit 0; }
else take_lock 0 || { log "No se pudo obtener el bloqueo $LOCK_FILE (otra instancia en marcha)."; exit 0; }; fi

TMPD=$(mktemp -d) || exit 1
trap 'rm -rf "$TMPD"; kill "${ZPID:-}" 2>/dev/null' EXIT

# ----------------------------------------------------------------------
# Red e índices
# ----------------------------------------------------------------------
hay_internet() {
    local url ip
    if command -v curl >/dev/null 2>&1; then
        for url in http://connectivity-check.ubuntu.com http://www.gstatic.com/generate_204 https://repo.quirinux.org; do
            curl -s -o /dev/null --connect-timeout 4 --max-time 8 "$url" && return 0
        done
    elif command -v wget >/dev/null 2>&1; then
        for url in http://connectivity-check.ubuntu.com http://www.gstatic.com/generate_204 https://repo.quirinux.org; do
            wget -q -O /dev/null --timeout=6 --tries=1 "$url" && return 0
        done
    fi
    for ip in repo.quirinux.org 1.1.1.1 8.8.8.8 9.9.9.9; do
        timeout 4 bash -c "exec 3<>/dev/tcp/$ip/443" >/dev/null 2>&1 && return 0
    done
    return 1
}

wait_for_network() {   # al iniciar sesión la red puede tardar en estar lista
    local waited=0
    while ! hay_internet; do
        [ "$INTERACTIVE" -eq 1 ] && return 1
        [ "$waited" -ge "$NET_WAIT" ] && return 1
        sleep 10; waited=$(( waited + 10 ))
    done
    return 0
}

# apt-get update como root, sin contraseña. Primero pkexec con el ayudante propio
# (el mismo camino que el comando "actualizar"; no necesita sudo, que no está en las
# dependencias del paquete). Escribe la salida en UPD_OUT y devuelve el código.
run_apt_update() {
    local rc=127
    UPD_OUT=""
    if command -v pkexec >/dev/null 2>&1 && [ -x "$ROOT_HELPER" ]; then
        UPD_OUT=$(pkexec "$ROOT_HELPER" update 2>&1); rc=$?
        [ "$rc" -eq 0 ] && return 0
        log "pkexec apt-get update falló (código $rc): $(printf '%s' "$UPD_OUT" | tr '\n' ' ' | cut -c1-200)"
    fi
    UPD_OUT="${UPD_OUT:-pkexec no disponible}"
    return "$rc"
}

refresh_indices() {
    [ "$REFRESH" -eq 1 ] && [ "$DRY" -eq 0 ] || return 0
    local now last try out rc=1
    now=$(date +%s); last=$(cat "$REFRESH_STAMP" 2>/dev/null || echo 0)
    [ "$last" -gt 0 ] 2>/dev/null || last=0
    if [ $(( now - last )) -lt "$REFRESH_EVERY" ] && [ "$INTERACTIVE" -eq 0 ]; then
        log "Índices recientes (hace $(( now - last )) s): no se actualizan."
        return 0
    fi
    # pkexec sin contraseña (polkit org.quirinux.update.run). Al iniciar sesión la
    # red puede estar "arriba" pero sin DNS o con apt ocupado (otro apt-get, unattended-
    # upgrades): se reintenta hasta 3 veces. Si no se consigue, se usan los índices que
    # ya hay y se deja el motivo en el registro.
    for try in 1 2 3; do
        run_apt_update; rc=$?
        [ "$rc" -eq 0 ] && break
        out=$(printf '%s' "$UPD_OUT" | tr '\n' ' ')
        log "apt-get update falló (código $rc, intento $try de 3): ${out:0:300}"
        [ "$try" -lt 3 ] && sleep 20
    done
    if [ "$rc" -eq 0 ]; then
        echo "$now" > "$REFRESH_STAMP"
        log "Índices de paquetes actualizados (apt-get update)."
    else
        log "No se pudo actualizar el índice; se usan los índices actuales."
    fi
}

# ----------------------------------------------------------------------
# Detección (sin permisos de administrador; misma lógica que quirinux-sync)
# ----------------------------------------------------------------------
ver_newer() {   # true si $1 es estrictamente más nuevo que $2
    [ "$1" != "$2" ] && [ "$(printf '%s\n%s\n' "$1" "$2" | sort -V | tail -n1)" = "$1" ]
}

in_suite() { apt-cache madison "$1" 2>/dev/null | grep -q " ${SUITE}/"; }

best_bpo_kernel() {
    local p
    for p in $(apt-cache pkgnames linux-image- 2>/dev/null | grep -E '^linux-image-[0-9][0-9.]*\+(bpo|deb[0-9]+)-amd64$'); do
        in_suite "$p" && echo "${p#linux-image-}"
    done | sort -V | tail -n1
}

newest_installed_kernel() {
    dpkg-query -W -f='${db:Status-Abbrev} ${Package}\n' 'linux-image-[0-9]*' 2>/dev/null \
        | awk '$1 ~ /^ii/ { sub("linux-image-", "", $2); print $2 }' | sort -V | tail -n1
}

detect_kernel() {   # escribe en PENDING_KERNEL la versión nueva, o vacío
    PENDING_KERNEL=""
    local best inst
    best=$(best_bpo_kernel); [ -n "$best" ] || return 0
    inst=$(newest_installed_kernel)
    if [ -z "$inst" ] || ver_newer "$best" "$inst"; then PENDING_KERNEL="$best"; fi
}

detect_packages() {   # escribe en $TMPD/pending los programas del wardrobe que faltan
    local wanted="$TMPD/wanted" installed="$TMPD/installed" missing="$TMPD/missing"
    grep -vE '^[[:space:]]*(#|$)' "$LIST_FILE" | awk '{print $1}' | sort -u > "$wanted"
    dpkg-query -W -f='${db:Status-Abbrev} ${Package}\n' 2>/dev/null \
        | awk '$1 ~ /^ii/ {print $2}' | sort -u > "$installed"
    comm -23 "$wanted" "$installed" > "$missing"
    : > "$TMPD/pending"
    if [ -s "$missing" ]; then
        # Solo los que tienen versión candidata en los repositorios de este sistema
        # shellcheck disable=SC2046
        apt-cache policy $(cat "$missing") 2>/dev/null \
            | awk '/^[^ ]/ {p=$1; sub(/:$/, "", p)} /^  Candidate:/ { if ($2 != "(none)") print p }' \
            | sort -u > "$TMPD/pending"
    fi
    # r8125/r8168 no se instalan con kernel >= 6.12 (los cubre r8169), como en quirinux-sync
    local k; k=$(newest_installed_kernel)
    if [ -n "$PENDING_KERNEL" ] && { [ -z "$k" ] || ver_newer "$PENDING_KERNEL" "$k"; }; then k="$PENDING_KERNEL"; fi
    if [ -n "$k" ] && dpkg --compare-versions "${k%%[+-]*}" ge 6.12 2>/dev/null; then
        grep -vxE 'r8125-dkms|r8168-dkms' "$TMPD/pending" > "$TMPD/pending.f" || true
        mv -f "$TMPD/pending.f" "$TMPD/pending"
    fi
    # Los que quirinux-sync ya intentó y no se pueden instalar en este equipo
    # (chocan con algo instalado, p. ej. grub-efi-amd64 en un equipo BIOS) no se
    # vuelven a ofrecer. Para reintentarlos: sudo quirinux-sync --force
    if [ -s "$OMIT_FILE" ] && [ -s "$TMPD/pending" ]; then
        awk 'NF {print $1}' "$OMIT_FILE" | sort -u > "$TMPD/omitted"
        comm -23 "$TMPD/pending" "$TMPD/omitted" > "$TMPD/pending.o" || true
        mv -f "$TMPD/pending.o" "$TMPD/pending"
    fi
}

# Actualizaciones del sistema (apt): misma lógica que "apt-get upgrade", en
# simulación y sin permisos de administrador. apt_all: líneas "paquete versión"
detect_apt() {
    : > "$TMPD/apt_all"
    apt-get -s -o Debug::NoLocking=1 upgrade 2>/dev/null \
        | awk '/^Inst [^ ]+ \[/ { p = $2; v = $0; sub(/^[^(]*\(/, "", v); split(v, a, " "); print p, a[1] }' \
        | sort -u > "$TMPD/apt_all"
}

# Flathub: programas instalados desde Flathub con una versión nueva.
# fp_all: líneas "ámbito aplicación commit"; fp_names: líneas "aplicación<TAB>nombre"
FLATPAK_BIN="${QUN_FLATPAK:-flatpak}"

detect_flatpak() {
    : > "$TMPD/fp_all"; : > "$TMPD/fp_names"
    command -v "$FLATPAK_BIN" >/dev/null 2>&1 || return 0
    [ "$NET_OK" -eq 1 ] || return 0
    local scope
    for scope in system user; do
        # El nombre va en la última columna para no depender del separador
        timeout 90 "$FLATPAK_BIN" remote-ls "--$scope" --updates --app \
            --columns=application,origin,commit,name 2>/dev/null \
            | awk -v s="$scope" '$2 ~ /^flathub/ && NF >= 3 {
                n = ""; for (i = 4; i <= NF; i++) n = n (i > 4 ? " " : "") $i
                print s, $1, $3, n }'
    done | sort -u > "$TMPD/fp_raw"
    awk '{print $1, $2, $3}' "$TMPD/fp_raw" | sort -u > "$TMPD/fp_all"
    awk '{ n = ""; for (i = 4; i <= NF; i++) n = n (i > 4 ? " " : "") $i
           print $2 "\t" (n == "" ? $2 : n) }' "$TMPD/fp_raw" | sort -u > "$TMPD/fp_names"
}

detect_local() { detect_kernel; detect_packages; detect_apt; }

# ----------------------------------------------------------------------
# Qué se muestra: todo lo pendiente, tanto al iniciar sesión como en modo
# interactivo (lo que el usuario dejó sin instalar se sigue anunciando).
# ----------------------------------------------------------------------
# Ya no se descuenta nada de lo que el usuario revisó y no instaló: al iniciar
# sesión se avisa siempre de todo lo que siga pendiente.
filter_dismissed() {   # $1 = todo  $2 = (sin uso)  $3 = salida
    cp "$1" "$3"
}

compute_show() {
    SHOW_KERNEL=""
    [ -n "$PENDING_KERNEL" ] && SHOW_KERNEL="$PENDING_KERNEL"
    filter_dismissed "$TMPD/pending"  "$DISMISSED_PKGS" "$TMPD/show"
    filter_dismissed "$TMPD/apt_all"  "$DISMISSED_APT"  "$TMPD/apt_show"
    filter_dismissed "$TMPD/fp_all"   "$DISMISSED_FP"   "$TMPD/fp_show"
    SHOW_COUNT=$(grep -c . "$TMPD/show" || true)
    APT_COUNT=$(grep -c . "$TMPD/apt_show" || true)
    FP_COUNT=$(grep -c . "$TMPD/fp_show" || true)
    TOTAL=$(( SHOW_COUNT + APT_COUNT + FP_COUNT + ( ${#SHOW_KERNEL} > 0 ? 1 : 0 ) ))
}

# Antes, tras la pantalla de selección se recordaba lo pendiente para no volver a
# avisar de ello al iniciar sesión, y "Revisar más tarde" silenciaba el resto del
# arranque. Ahora se avisa siempre mientras haya actualizaciones: estas funciones
# se conservan sin efecto por compatibilidad.
remember_current() { return 0; }
remember_later()   { return 0; }

# ----------------------------------------------------------------------
# Interfaz
# ----------------------------------------------------------------------
# zenity, yad y notify-send se ejecutan con el locale del usuario, no con
# LC_ALL=C (que solo sirve para analizar la salida de apt/dpkg): en C los
# textos con acentos no se pueden convertir y no se abre la ventana.
ui() {
    if [ -n "$_ORIG_LC_ALL" ]; then LC_ALL="$_ORIG_LC_ALL" "$@"
    else env -u LC_ALL "$@"; fi
}

info() {   # $1 = info|error|warning  $2 = texto
    command -v zenity >/dev/null 2>&1 || return 0
    ui zenity "--$1" --no-markup --title="$L_title" --text="$2" --width=440 >/dev/null 2>&1 || true
}

notification_text() {
    # shellcheck disable=SC2059
    printf "$L_N_BODY" "$TOTAL"
}

notify_user() {   # escribe en stdout: review | later | unseen
    local text out rc=1 try t0 elapsed
    text=$(notification_text)
    if command -v notify-send >/dev/null 2>&1; then
        for try in 1 2 3 4; do
            t0=$SECONDS; : > "$TMPD/notify.err"
            # Urgencia "critical" + expire-time=0: la notificación se queda en pantalla
            # hasta que el usuario hace clic (con "normal", muchos servidores de
            # notificaciones la retiran solos tras unos segundos e ignoran expire-time).
            # Solo se define la acción "review" (un único botón). Si además se definía
            # "default", servidores como xfce4-notifyd la dibujaban como un segundo botón
            # "Revisar". "default" se sigue aceptando abajo por si algún servidor la envía.
            out=$(ui timeout 86400 notify-send --wait --urgency=critical --icon="$ICON" \
                    --app-name="Quirinux Update" --expire-time=0 \
                    --action="review=$L_B_REVIEW" \
                    "$L_N_TITLE" "$text" 2>>"$TMPD/notify.err"); rc=$?
            elapsed=$(( SECONDS - t0 ))
            if [ "$rc" -eq 0 ]; then
                if [ "$out" = review ] || [ "$out" = default ]; then echo review; return; fi
                if [ "$elapsed" -ge 5 ]; then echo later; return; fi   # cerrada o ignorada por el usuario
                # Cerrada casi al instante: no la cerró el usuario (el servidor de
                # notificaciones aún no estaba listo o la sesión seguía cargando).
                log "La notificación se cerró a los ${elapsed}s sin respuesta (intento $try de 4)."
            elif [ "$rc" -eq 124 ]; then
                echo later; return
            else
                # Servidor de notificaciones aún no disponible al iniciar sesión: se reintenta
                log "notify-send falló (código $rc, intento $try de 4): $(tr '\n' ' ' < "$TMPD/notify.err" 2>/dev/null)"
            fi
            [ "$try" -lt 4 ] && sleep 15
        done
    fi
    # Sin notify-send, o un servidor de notificaciones que no responde: el mismo aviso en una ventana
    if command -v yad >/dev/null 2>&1; then
        log "Se avisa con una ventana (yad) porque la notificación no se pudo mostrar."
        ui yad --title="$L_N_TITLE" --text="$text" --image="$ICON" --center \
            --window-icon="$ICON" --width=380 --on-top \
            --button="$L_B_REVIEW:0" >/dev/null 2>&1
        case $? in 0) echo review ;; *) echo later ;; esac
        return
    fi
    log "No se pudo mostrar el aviso (ni notify-send ni yad funcionan)."
    if [ "$rc" -eq 0 ]; then echo unseen; else echo later; fi
}

# Descripciones breves (una sola llamada a apt) de programas nuevos y actualizaciones
build_descriptions() {   # escribe $TMPD/desc: "paquete<TAB>descripción"
    : > "$TMPD/desc"
    { cat "$TMPD/show"; awk '{print $1}' "$TMPD/apt_show"; } | awk 'NF' | sort -u > "$TMPD/desc.names"
    [ -s "$TMPD/desc.names" ] || return 0
    # shellcheck disable=SC2046
    apt-cache show --no-all-versions $(cat "$TMPD/desc.names") 2>/dev/null | awk '
        /^Package: /     { p = substr($0, 10) }
        /^Description(-[a-z]+)?: / && p != "" {
            d = $0; sub(/^[^:]*: /, "", d); print p "\t" d; p = "" }' > "$TMPD/desc"
}

# Origen de cada paquete según su versión candidata: "Quirinux" si viene de
# repo.quirinux.org y "Sistema base" en cualquier otro caso. Escribe en
# $TMPD/qx los paquetes que vienen de Quirinux.
build_origins() {
    : > "$TMPD/qx"
    [ -s "$TMPD/desc.names" ] || return 0
    # shellcheck disable=SC2046
    apt-cache policy $(cat "$TMPD/desc.names") 2>/dev/null | awk '
        /^[^ ]/            { p = $1; sub(/:$/, "", p); cand = ""; incand = 0; next }
        /^  Candidate:/    { cand = $2; next }
        /^ \*\*\* [^ ]/     { incand = ($2 == cand); next }
        /^     [^ ]/       { incand = ($1 == cand); next }
        /^        /        { if (incand && index($0, "repo.quirinux.org")) print p }' \
        | sort -u > "$TMPD/qx"
}

origin_of() {   # $1 = paquete apt  $2 = apt | wd
    case "$2:$1" in
        apt:linux-image-*|apt:linux-headers-*|apt:linux-kbuild-*) printf '%s' "$L_T_KERNEL"; return ;;
    esac
    local o="$L_T_SYS"
    grep -qxF -- "$1" "$TMPD/qx" 2>/dev/null && o="$L_T_QX"
    # Los programas nuevos añaden "¡Novedad!" al origen (Sistema base o Quirinux)
    if [ "$2" = wd ]; then printf '%s · %s' "$o" "$L_T_NEW"; else printf '%s' "$o"; fi
}

# Filas de la lista (5 líneas por fila: casilla, id, nombre, descripción, origen).
# Identificadores: kernel:<versión>, apt:<paquete>, wd:<paquete>, fp:<ámbito>:<aplicación>
build_rows() {
    build_descriptions
    build_origins
    local rows="$TMPD/rows" scope app commit ver name d scope_l
    : > "$rows"
    row() { printf '%s\n' TRUE "$1" "$2" "$3" "$4" >> "$rows"; }   # id nombre descripción origen
    if [ -n "$SHOW_KERNEL" ]; then
        # shellcheck disable=SC2059
        row "kernel:$SHOW_KERNEL" "linux-image-$SHOW_KERNEL" "$(printf "$L_N_KERNEL" "$SHOW_KERNEL")" "$L_T_KERNEL"
    fi
    while read -r app ver; do
        [ -n "$app" ] || continue
        d=$(awk -F'\t' -v p="$app" '$1 == p { print $2; exit }' "$TMPD/desc" | tr '|' '/')
        row "apt:$app" "$app" "$d" "$(origin_of "$app" apt)"
    done < "$TMPD/apt_show"
    while IFS= read -r app; do
        [ -n "$app" ] || continue
        d=$(awk -F'\t' -v p="$app" '$1 == p { print $2; exit }' "$TMPD/desc" | tr '|' '/')
        row "wd:$app" "$app" "$d" "$(origin_of "$app" wd)"
    done < "$TMPD/show"
    while read -r scope app commit; do
        [ -n "$app" ] || continue
        name=$(awk -F'\t' -v a="$app" '$1 == a { print $2; exit }' "$TMPD/fp_names" | tr '|' '/')
        case "$scope" in system) scope_l="$L_FP_SCOPE_SYS" ;; *) scope_l="$L_FP_SCOPE_USER" ;; esac
        row "fp:$scope:$app" "${name:-$app}" "$app ($scope_l)" "$L_T_FP"
    done < "$TMPD/fp_show"
}

# Pantalla de selección. Escribe los identificadores marcados en $TMPD/selected.
# Devuelve 0 si el usuario acepta, 1 si cancela o cierra la ventana.
select_window() {
    command -v yad >/dev/null 2>&1 || { log "yad no está instalado: no se puede mostrar la pantalla."; return 1; }
    build_rows
    local rows="$TMPD/rows"
    local out rc
    out=$(ui yad --list --checklist --title="$L_W_TITLE" --text="$L_W_TEXT" \
            --window-icon=system-software-update --center --width=860 --height=560 \
            --column=":CHK" --column="ID" --column="$L_C_NAME" --column="$L_C_DESC" --column="$L_C_ORIGIN" \
            --hide-column=2 --search-column=3 --separator='|' \
            --button="$L_B_CANCEL!gtk-cancel:1" --button="$L_B_INSTALL!gtk-ok:0" \
            < "$rows" 2>>"$TMPD/yad.err"); rc=$?
    if [ "$rc" -ne 0 ]; then
        [ "$rc" -gt 1 ] && [ "$rc" -ne 252 ] && log "yad falló (código $rc): $(tr '\n' ' ' < "$TMPD/yad.err" 2>/dev/null)"
        return 1
    fi
    # Solo filas marcadas, por si esta versión de yad imprime todas
    printf '%s\n' "$out" | awk -F'|' '$1 == "TRUE" && $2 != "" { print $2 }' > "$TMPD/selected"
    return 0
}

# ----------------------------------------------------------------------
# Aplicar la selección
# ----------------------------------------------------------------------
ZPID=""
progress_start() {
    command -v zenity >/dev/null 2>&1 && mkfifo "$TMPD/progress.fifo" 2>/dev/null || return 0
    ui zenity --progress --pulsate --no-cancel --title="$L_WORKING_T" --text="$L_WORKING" \
        --width=440 < "$TMPD/progress.fifo" >/dev/null 2>&1 &
    ZPID=$!
    exec 8>"$TMPD/progress.fifo"
}
progress_stop() {
    [ -n "$ZPID" ] || return 0
    exec 8>&-
    # "ui zenity &" lanza un proceso intermedio: se cierran también sus hijos
    pkill -TERM -P "$ZPID" 2>/dev/null
    kill "$ZPID" 2>/dev/null
    wait "$ZPID" 2>/dev/null
    ZPID=""
}

sync_field() { [ -f "$SYNC_STATE" ] && sed -n "s/^$1=//p" "$SYNC_STATE" | tail -n1; return 0; }
res_field()  { sed -n 's/^RESULT:.*\b'"$1"'=\(-\{0,1\}[0-9]\{1,\}\).*/\1/p' "$TMPD/apply.out" 2>/dev/null | tail -n1; }

# Códigos: -1 = no se tocó, 0 = bien, 126/127 = autenticación cancelada, otro = fallo
apply_selection() {
    RC_UFP=-1; RC_ROOT=-1; R_APT=-1; R_SYNC=-1; R_FP=-1
    local -a user_apps=()
    mapfile -t user_apps < <(sed -n 's/^fp:user://p' "$TMPD/selected")
    if [ "${#user_apps[@]}" -gt 0 ]; then
        log "Flatpak (usuario): ${user_apps[*]}"
        timeout 7200 "$FLATPAK_BIN" update --user -y --noninteractive "${user_apps[@]}"; RC_UFP=$?
    fi
    # Todo lo que necesita administrador (apt, wardrobe, kernel, Flatpak del
    # sistema) se aplica de una vez, sin petición de contraseña (polkit)
    if grep -qE '^(kernel|wd|apt):|^fp:system:' "$TMPD/selected"; then
        chmod 0755 "$TMPD"; chmod 0644 "$TMPD/selected"     # lo lee quirinux-update-apply como root
        log "Aplicando como administrador: $(grep -c . "$TMPD/selected") elementos"
        DEBIAN_FRONTEND=noninteractive timeout 7200 ${QUN_PKEXEC:-pkexec} "$APPLY_BIN" "$TMPD/selected" \
            > "$TMPD/apply.out" 2>>"$TMPD/apply.err"; RC_ROOT=$?
        log "quirinux-update-apply terminó con código $RC_ROOT: $(grep '^RESULT:' "$TMPD/apply.out" | tail -n1)"
        if [ "$RC_ROOT" -ne 126 ] && [ "$RC_ROOT" -ne 127 ]; then
            R_APT=$(res_field apt); R_SYNC=$(res_field sync); R_FP=$(res_field fp)
            R_APT=${R_APT:--1}; R_SYNC=${R_SYNC:--1}; R_FP=${R_FP:--1}
        fi
    fi
}

show_result() {
    local msg=""
    # Autenticación cancelada: no se instaló nada de administrador; no se dice nada
    if [ "$RC_ROOT" -eq 126 ] || [ "$RC_ROOT" -eq 127 ]; then
        # shellcheck disable=SC2059
        [ "$RC_UFP" -gt 0 ] && info error "$(printf "$L_FAIL" "$LOG_FILE")"
        return 0
    fi
    # shellcheck disable=SC2059
    if [ "$R_SYNC" -gt 0 ]; then info error "$(printf "$L_FAIL" "$SYNC_LOG")"; return 0; fi
    # shellcheck disable=SC2059
    if [ "$R_APT" -gt 0 ] || [ "$R_FP" -gt 0 ] || [ "$RC_UFP" -gt 0 ] || { [ "$RC_ROOT" -gt 0 ] && [ "$R_APT$R_SYNC$R_FP" = "-1-1-1" ]; }; then
        info error "$(printf "$L_FAIL" "$APPLY_LOG")"; return 0
    fi
    if [ "$R_SYNC" -ge 0 ]; then
        case "$(sync_field KERNEL)" in instalado:*) msg="$L_DONE_REBOOT" ;; esac
        if [ -z "$msg" ]; then
            # shellcheck disable=SC2059
            case "$(sync_field STATUS)" in partial|failed) msg="$(printf "$L_DONE_PART" "$SYNC_LOG")" ;; esac
        fi
    fi
    info info "${msg:-$L_DONE_OK}"
}

# Pantalla de selección + aplicar. Devuelve 0 si el usuario aceptó, 1 si canceló.
review_flow() {
    if [ "$DRY" -eq 1 ]; then
        printf -- '--- Se abriría la pantalla de selección con (todo marcado):\n'
        build_rows
        paste -d'|' - - - - - < "$TMPD/rows" | awk -F'|' '{ print "  [" $5 "] " $3 " - " $4 }'
        return 0
    fi
    select_window || { log "Pantalla de selección cancelada."; return 1; }
    local n; n=$(grep -c . "$TMPD/selected" || true)
    log "Selección aceptada: $n elementos."
    if [ "$n" -gt 0 ]; then
        progress_start
        apply_selection
        progress_stop
        # Lo que se dejó sin marcar, o no se pudo instalar, no se vuelve a anunciar al
        # iniciar sesión hasta que haya algo más nuevo (quirinux-update lo sigue mostrando)
        if [ "$RC_ROOT" -ne 126 ] && [ "$RC_ROOT" -ne 127 ]; then remember_current; fi
        show_result
    else
        remember_current
    fi
    return 0
}

# ----------------------------------------------------------------------
# Ejecución
# ----------------------------------------------------------------------
NET_OK=1
if [ "$DRY" -eq 0 ]; then
    if ! wait_for_network; then
        NET_OK=0
        log "Sin conexión a Internet: se omite Flatpak y se usan los índices que ya hay."
    fi
fi

# Con red ya disponible: se actualiza el índice (antes de esto se intentaba sin red al
# iniciar sesión y se detectaba con índices viejos o vacíos)
[ "$NET_OK" -eq 1 ] && refresh_indices

detect_local
detect_flatpak
compute_show
log "Modo $([ "$INTERACTIVE" -eq 1 ] && echo interactivo || echo inicio-de-sesión): kernel='${SHOW_KERNEL:-}' sistema=$APT_COUNT programas-nuevos=$SHOW_COUNT flatpak=$FP_COUNT"

if [ "$TOTAL" -eq 0 ]; then
    if [ "$INTERACTIVE" -eq 1 ] && [ "$DRY" -eq 0 ]; then
        if [ "$NET_OK" -eq 1 ]; then info info "$L_UPTODATE"; else info warning "$L_NO_NET"; fi
    fi
    exit 0
fi

# --- quirinux-update: directo a la pantalla de selección -----------------
if [ "$INTERACTIVE" -eq 1 ]; then
    review_flow
    exit 0
fi

# --- Inicio de sesión: una sola notificación -----------------------------
if [ "$DRY" -eq 1 ]; then
    printf -- '--- Notificación [%s] icono=%s\n%s\n%s\n' "$L_B_REVIEW" "$ICON" "$L_N_TITLE" "$(notification_text)"
    review_flow
    exit 0
fi

release_lock
answer=$(notify_user)
log "Respuesta a la notificación: $answer"
if [ "$answer" = unseen ]; then
    log "No se llegó a ver la notificación: se volverá a avisar en el próximo inicio de sesión."
elif [ "$answer" = review ]; then
    # Puede haber cambiado algo mientras la notificación esperaba (p. ej. se usó quirinux-update)
    take_lock 0 || exit 0
    detect_local; compute_show
    [ "$TOTAL" -gt 0 ] || exit 0
    review_flow || remember_later
else
    remember_later
fi
exit 0
