#!/bin/bash

# ======================================================================
# Archivo:       instalar-recomendados
# Ruta:          /usr/local/bin/
# Autor:         Charlie Martínez® <cmartinez@quirinux.org>
# Licencia:      https://www.gnu.org/licenses/gpl-2.0.txt
# Propósito:     Instalador de programas recomendados
# 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

# ----------------------------------------------------------------------
# Traducciones
# ----------------------------------------------------------------------

function _inicioEn() { zenity --info --text "You are using Quirinux from a USB Pendrive and will only be able to install the recommended additional software once you have installed Quirinux on your disk."; }
function _inicioEs() { zenity --info --text "Estás usando Quirinux desde un Pendrive USB y sólo podrás instalar el software adicional recomendado una vez que hayas instalado Quirinux en tu disco."; }
function _inicioGl() { zenity --info --text "Estás usando Quirinux desde un Pendrive USB e só poderás instalar o software adicional recomendado unha vez que instalaches Quirinux no teu disco."; }
function _inicioDe() { zenity --info --text "Sie verwenden Quirinux von einem USB-Flash-Laufwerk und können die empfohlene zusätzliche Software erst installieren, nachdem Sie Quirinux auf Ihrer Festplatte installiert haben."; }
function _inicioPt() { zenity --info --text "Você está usando o Quirinux de um pendrive USB e só poderá instalar o software adicional recomendado depois de instalar o Quirinux no seu disco."; }
function _inicioIt() { zenity --info --text "Stai utilizzando Quirinux da una chiavetta USB e potrai installare il software aggiuntivo consigliato solo dopo aver installato Quirinux sul tuo disco."; }
function _inicioFr() { zenity --info --text "Vous utilisez Quirinux à partir d'une clé USB et vous ne pourrez installer le logiciel supplémentaire recommandé qu'après avoir installé Quirinux sur votre disque."; }
function _inicioRu() { zenity --info --text "Вы используете Quirinux с USB-накопителя и сможете установить рекомендуемое дополнительное программное обеспечение только после установки Quirinux на диск."; }
function _inicioHu() { zenity --info --text "Quirinuxot USB-pendrive-ról használod, és az ajánlott szoftvereket csak akkor tudod telepíteni, ha a Quirinuxot a lemezedre telepítetted."; }

function _noInternetEn() { zenity --warning --text "No Internet connection detected. Please connect to the Internet before proceeding."; }
function _noInternetEs() { zenity --warning --text "No se detectó conexión a Internet. Por favor, conecta a Internet antes de continuar."; }
function _noInternetGl() { zenity --warning --text "Non se detectou conexión a Internet. Conéctate a Internet antes de continuar."; }
function _noInternetDe() { zenity --warning --text "Keine Internetverbindung erkannt. Bitte verbinden Sie sich mit dem Internet, bevor Sie fortfahren."; }
function _noInternetPt() { zenity --warning --text "Nenhuma conexão com a Internet detectada. Por favor, conecte-se à Internet antes de prosseguir."; }
function _noInternetIt() { zenity --warning --text "Nessuna connessione Internet rilevata. Si prega di connettersi a Internet prima di procedere."; }
function _noInternetFr() { zenity --warning --text "Aucune connexion Internet détectée. Veuillez vous connecter à Internet avant de continuer."; }
function _noInternetRu() { zenity --warning --text "Интернет-соединение не обнаружено. Пожалуйста, подключитесь к Интернету перед продолжением."; }
function _noInternetHu() { zenity --warning --text "Nem található internetkapcsolat. Kérjük, csatlakozz az internethez a folytatás előtt."; }

# =========================================================================================
# SELECTOR DE IDIOMA [CÓDIGO REUTILIZABLE]
# Esta sección fue tomada de Etertics GNU/Linux,
# @Autor: Javier Obregón (GPLv3)
# =========================================================================================

function _idioma() { IDIOMA=$(echo $LANG | cut -d_ -f1); }

function _mensajeInicio() {
    case "$IDIOMA" in
        es) _inicioEs ;; gl) _inicioGl ;; pt) _inicioPt ;;
        fr) _inicioFr ;; it) _inicioIt ;; de) _inicioDe ;;
        ru) _inicioRu ;; hu) _inicioHu ;; *)  _inicioEn ;;
    esac
}

function _mensajeNoInternet() {
    case "$IDIOMA" in
        es) _noInternetEs ;; gl) _noInternetGl ;; pt) _noInternetPt ;;
        fr) _noInternetFr ;; it) _noInternetIt ;; de) _noInternetDe ;;
        ru) _noInternetRu ;; hu) _noInternetHu ;; *)  _noInternetEn ;;
    esac
}

function _mensajeInstalados() {
    case "$IDIOMA" in
        es) _instaladosEs ;; gl) _instaladosGl ;; pt) _instaladosPt ;;
        fr) _instaladosFr ;; it) _instaladosIt ;; de) _instaladosDe ;;
        ru) _instaladosRu ;; hu) _instaladosHu ;; *)  _instaladosEn ;;
    esac
}

# =========================================================================================
# COMPROBACIÓN DE INTERNET [CÓDIGO REUTILIZABLE]
# Antes se hacía solo "ping -c 1 google.com", que falla en sistemas recién instalados
# cuando ICMP está filtrado, ping no tiene permisos/no está instalado, o el DNS aún
# no responde. Ahora se prueban varios métodos con timeout corto; basta con que uno funcione.
# =========================================================================================

function _hayInternet()
{
    local url
    local urls="http://connectivity-check.ubuntu.com http://detectportal.firefox.com/success.txt http://www.gstatic.com/generate_204 https://www.debian.org"

    # 1. HTTP(S) con curl o wget (respeta proxies del entorno)
    if command -v curl >/dev/null 2>&1; then
        for url in $urls; 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 $urls; do
            wget -q -O /dev/null --timeout=6 --tries=1 "$url" && return 0
        done
    fi

    # 2. Python (siempre presente: mintinstall depende de python3)
    if command -v python3 >/dev/null 2>&1; then
        python3 -I - $urls >/dev/null 2>&1 <<'PYEOF' && return 0
import sys, urllib.request
for u in sys.argv[1:]:
    try:
        urllib.request.urlopen(u, timeout=6)
        sys.exit(0)
    except Exception:
        pass
sys.exit(1)
PYEOF
    fi

    # 3. Conexión TCP directa a IPs conocidas (no depende de DNS ni de ICMP)
    local ip
    for ip in 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

    # 4. ICMP como último recurso
    for ip in 1.1.1.1 8.8.8.8 google.com; do
        ping -c 1 -W 3 "$ip" >/dev/null 2>&1 && return 0
    done

    return 1
}

# =========================================================================================
# DETECCIÓN DE SISTEMA LIVE [CÓDIGO REUTILIZABLE]
# Comprueba boot=live en /proc/cmdline y, como respaldo, el punto de montaje
# del medio live creado por live-boot. No se comprueba la existencia de /usr/bin/eggs:
# ese paquete también está presente en sistemas ya instalados en disco.
# =========================================================================================

function _esSistemaLive()
{
    if grep -qs 'boot=live' /proc/cmdline; then
        return 0
    elif [ -d /run/live/medium ] || [ -d /lib/live/mount/medium ]; then
        return 0
    else
        return 1
    fi
}

# ----------------------------------------------------------------------
# LÓGICA PRINCIPAL
# Todo lo que sigue corre como usuario normal (con display disponible)
# ----------------------------------------------------------------------

_idioma

# 2. ¿Estamos corriendo desde un pendrive (live)?
if _esSistemaLive; then
    _mensajeInicio
    exit 0
fi

# 3. ¿Hay conexión a Internet?
if ! _hayInternet; then
    _mensajeNoInternet
    exit 0
fi

# 4. Todo OK: conceder permiso gráfico a root y elevar privilegios
# xhost se ejecuta AQUÍ, como usuario normal, antes de pkexec
xhost +local:root 2>/dev/null || true

# pkexec ejecuta el wrapper que hace apt-get update y abre el instalador
# Se pasan DISPLAY y XAUTHORITY al wrapper porque pkexec limpia el entorno
pkexec /usr/local/bin/abrir-recomendados-wrapper "${DISPLAY:-:0}" "${XAUTHORITY:-}"
