#!/bin/bash

# Nombre:    instalar-recomendados.sh
# Autor:    Charlie Martínez® <cmartinez@quirinux.org>
# Licencia:    https://www.gnu.org/licenses/gpl-3.0.txt
# Descripción:    Revisa requisitos para ejecutar la aplicacion "recomendados" de Quirinux.
# Versión:    2.4

# =========================================================================================
# INICIO / FIN (IDIOMAS) [CÓDIGO REUTILIZABLE]
# =========================================================================================

function _inicioEn()
{
    zenity --info --text "You are using Quirinux from a USB Pendrive and will only be able to open the Software Center to install more programs 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 abrir el Centro de Software para instalar más programas una vez que hayas instalado Quirinux en tu disco."
}

function _inicioGl()
{
    zenity --info --text "Estás a usar Quirinux desde un Pendrive USB e só poderás abrir o Centro de Software para instalar máis programas unha vez que instalaches Quirinux no teu disco."
}

function _inicioDe()
{
    zenity --info --text "Sie verwenden Quirinux von einem USB-Stick und können das Software-Center erst öffnen, um weitere Programme zu installieren, nachdem Sie Quirinux auf Ihrer Festplatte installiert haben."
}

function _inicioPt()
{
    zenity --info --text "Você está usando o Quirinux a partir de um pendrive USB e só poderá abrir o Centro de Software para instalar mais programas depois de instalar o Quirinux no seu disco."
}

function _inicioIt()
{
    zenity --info --text "Stai utilizzando Quirinux da una chiavetta USB e potrai aprire il Centro Software per installare altri programmi solo dopo aver installato Quirinux sul tuo disco."
}

function _inicioFr()
{
    zenity --info --text "Vous utilisez Quirinux depuis une clé USB et vous ne pourrez ouvrir le Centre de logiciels pour installer d'autres programmes qu'après avoir installé Quirinux sur votre disque."
}

function _inicioRu()
{
    zenity --info --text "Вы используете Quirinux с USB-накопителя и сможете открыть Центр программ для установки дополнительных приложений только после установки Quirinux на диск."
}

function _inicioHu()
{
    zenity --info --text "A Quirinux-ot egy USB-meghajtóról használja, és a Szoftverközpontot csak akkor nyithatja meg további programok telepítéséhez, ha már telepítette a Quirinux-ot a merevlemezére."
}


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 észlelhető internetkapcsolat. Kérjük, csatlakozzon 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) # Idioma del sistema
}

function _mensajeInicio()
{
    if [[ $IDIOMA = "es" ]]; then
        _inicioEs
    elif [[ $IDIOMA = "en" ]]; then
        _inicioEn
    elif [[ $IDIOMA = "gl" ]]; then
        _inicioGl
    elif [[ $IDIOMA = "pt" ]]; then
        _inicioPt
    elif [[ $IDIOMA = "fr" ]]; then
        _inicioFr
    elif [[ $IDIOMA = "it" ]]; then
        _inicioIt
    elif [[ $IDIOMA = "de" ]]; then
        _inicioDe
    elif [[ $IDIOMA = "ru" ]]; then
        _inicioRu
    elif [[ $IDIOMA = "hu" ]]; then
        _inicioHu
    else
        _inicioEn
    fi
}

function _mensajeNoInternet()
{
    if [[ $IDIOMA = "es" ]]; then
        _noInternetEs
    elif [[ $IDIOMA = "en" ]]; then
        _noInternetEn
    elif [[ $IDIOMA = "gl" ]]; then
        _noInternetGl
    elif [[ $IDIOMA = "pt" ]]; then
        _noInternetPt
    elif [[ $IDIOMA = "fr" ]]; then
        _noInternetFr
    elif [[ $IDIOMA = "it" ]]; then
        _noInternetIt
    elif [[ $IDIOMA = "de" ]]; then
        _noInternetDe
    elif [[ $IDIOMA = "ru" ]]; then
        _noInternetRu
    elif [[ $IDIOMA = "hu" ]]; then
        _noInternetHu
    else
        _noInternetEn
    fi
}

# =========================================================================================
# 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. Más robusto que comprobar la existencia
# de un paquete concreto (p.ej. eggs), que puede estar presente también en
# sistemas ya instalados.
# =========================================================================================

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
}

# =========================================================================================
# 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
}

# Detectar el idioma del sistema
_idioma


# Verificar si el sistema es una sesión live
if _esSistemaLive; then
    # Ejecutar la función _mensajeInicio si el sistema es live
    _mensajeInicio
else
    # Comprobar la conexión a Internet
    if _hayInternet; then
        # Ejecutar apt-get update si hay conexión a Internet
        sudo apt-get update
        # Abrir el centro de software.
	abrir-mintinstall-ok
    else
        # Mostrar advertencia de falta de conexión a Internet
        _mensajeNoInternet
    fi
fi
