#!/bin/bash
txtred=$(tput bold ; tput setaf 1) 
txtgreen=$(tput bold ; tput setaf 2) 
txtyellow=$(tput bold ; tput setaf 3) 
clear

# Definición de colores (opcional, para resaltar)
GREEN='\033[0;32m'
NC='\033[0m' # No Color

satlink_info() {
  clear
  cat <<"EOF"
              https://t.me/Satlink502
███████╗ █████╗ ████████╗██╗     ██╗███╗   ██╗██╗  ██╗
██╔════╝██╔══██╗╚══██╔══╝██║     ██║████╗  ██║██║ ██╔╝
███████╗███████║   ██║   ██║     ██║██╔██╗ ██║█████╔╝
╚════██║██╔══██║   ██║   ██║     ██║██║╚██╗██║██╔═██╗
███████║██║  ██║   ██║   ███████╗██║██║ ╚████║██║  ██╗
╚══════╝╚═╝  ╚═╝   ╚═╝   ╚══════╝╚═╝╚═╝  ╚═══╝╚═╝  ╚═╝
IPTV-CATV-RESTREAM                  info@satlink.com.gt
EOF
}

items=(1 "INSTALAR DRIVERS TBS"
       2 "INSTALAR ASTRA-LATEST"
       3 "ACTUALIZAR A ASTRA-SATLINK"
       4 "BACKUP ASTRA-SATLINK"
       5 "LICENCIA ASTRA-SATLINK"
       6 "ACTIVAR UDP"
       7 "DESINSTALAR ASTRA")

while choice=$(dialog --title "SATLINK" \
                      --backtitle "https://t.me/Satlink502" \
                      --menu "MENU DE INSTALACION V.2" 18 35 7 "${items[@]}" \
                 2>&1 >/dev/tty)
    do
    case $choice in
        1)
echo -e "┌────── SATLINK MENU INSTALL - https://t.me/Satlink502 ─────┐ "
echo -e "             ${GREEN}Iniciando la instalación...${NC}         "
echo -e "└───────────────────────────────────────────────────────────┘ "

cd / ; curl -sSf https://cdn.cesbo.com/astra/scripts/drv-tbs.sh | sh && echo "" > ~/.bash_history && history -c ; clear

echo -e "┌────── SATLINK MENU INSTALL - https://t.me/Satlink502 ─────┐ "
echo -e "               ${GREEN}Instalación completada.${NC}           "
echo -e "└───────────────────────────────────────────────────────────┘ "

satlink_info

sleep 3s

        ;;

        2)
echo -e "┌────── SATLINK MENU INSTALL - https://t.me/Satlink502 ─────┐ "
echo -e "             ${GREEN}Iniciando la instalación...${NC}         "
echo -e "└───────────────────────────────────────────────────────────┘ "

cd / ; curl -Lo /usr/bin/astra http://cesbo.com/and/astra-250612 ; chmod +x /usr/bin/astra && cd / ; mkdir -p /etc/astra && cd /etc/astra/ ; echo "Introduzca su licencia de ASTRA" ; read keyastra && curl -o /etc/astra/license.txt https://cesbo.com/astra-license/$keyastra && astra init ; systemctl start astra ; systemctl enable astra ; echo "" > ~/.bash_history && history -c ; clear

echo -e "┌────── SATLINK MENU INSTALL - https://t.me/Satlink502 ─────┐ "
echo -e "               ${GREEN}Instalación completada.${NC}           "
echo -e "└───────────────────────────────────────────────────────────┘ "
sleep 3s 

echo -e "┌────── SATLINK MENU INSTALL - https://t.me/Satlink502 ─────┐ "
echo -e "             ${GREEN}Instalando Logotipos...${NC}         "
echo -e "└───────────────────────────────────────────────────────────┘ "

mkdir -m 777 /var/lib/astra/tvg-logo/ ; cd /var/lib/astra/tvg-logo/ ; wget https://github.com/SatlinkGT/LOGOS/raw/main/logos70w.zip ; unzip logos70w.zip ; echo "" > ~/.bash_history && history -c ; clear

echo -e "┌────── SATLINK MENU INSTALL - https://t.me/Satlink502 ─────┐ "
echo -e "               ${GREEN}Instalación completada.${NC}           "
echo -e "└───────────────────────────────────────────────────────────┘ "
sleep 3s 

        ;;

        3)

satlink_info
echo "${txtyellow} ┌──────────────────────────────────────┐ "
echo "${txtyellow} │        INSTALANDO ASTRA-SATLINK       │ "
echo "${txtyellow} └──────────────────────────────────────┘ "
# ==============================================
# CONFIGURACIÓN INICIAL
# ==============================================

export TZ='America/Guatemala'
SERVER_IP=""
CLOUD_NAME="SATLINK Cloud"

# ==============================================
# FUNCIONES UTILITARIAS
# ==============================================
function display_message() {
    echo -e "\033[1;36m$1\033[0m"
}

function handle_service() {
    # Verificar si el servicio existe
    if systemctl list-unit-files | grep -q 'astra\.service'; then
        case $1 in
            stop)
                echo -e "\033[1;36m• Deteniendo servicio Astra...\033[0m"
                systemctl stop astra
                ;;
            enable)
                echo -e "\033[1;36m• Habilitando inicio automático...\033[0m"
                systemctl enable astra && echo -e "\033[1;32m  ✓ Servicio habilitado\033[0m" || echo -e "\033[1;31m  ✗ Error al habilitar\033[0m"
                ;;
            restart)
                echo -e "\033[1;36m• Reiniciando servicio...\033[0m"
                systemctl restart astra && echo -e "\033[1;32m  ✓ Servicio reiniciado\033[0m" || echo -e "\033[1;31m  ✗ Error al reiniciar\033[0m"
                ;;
        esac
        sleep 1
    else
        echo -e "\033[1;33m• Servicio Astra no instalado (omitido)\033[0m"
    fi
}

# ==============================================
# INICIO DEL PROCESO
# ==============================================

clear
echo -e "\033[1;34m========================================\033[0m"
echo -e "\033[1;34m    ACTUALIZACIÓN ASTRA - SATLINK    \033[0m"
echo -e "\033[1;34m========================================\033[0m"

# 1. Manejo del servicio
handle_service stop

# ==============================================
# PROCESO DE ACTUALIZACIÓN
# ==============================================

SUMMARY=""

# 2. Verificar instalación existente
if [ ! -f "/usr/bin/astra" ]; then
    display_message "\n• Astra no está instalado en este equipo"
    display_message "• Se procederá a descargar la actualización"
    display_message "• No se realizará respaldo previo"
+="• No existía instalación previa\n"
else
    # 3. Proceso de respaldo
    BACKUP_NAME="astraresp_$(date '+%Y%m%d-%H%M%S').bin"
    mv "/usr/bin/astra" "/usr/bin/$BACKUP_NAME" 2>/dev/null
    
    display_message "\n• Respaldo local creado exitosamente"

    # 4. Subida a la nube
    # display_message "\n• Subiendo a $CLOUD_NAME..."
    # RESPONSE=$(curl -s -F "file=@/usr/bin/$BACKUP_NAME" "http://$SERVER_IP/config/astra.php")
    
    if [[ $RESPONSE == *"Éxito:"* ]]; then
        display_message "  ✓ Subido a $CLOUD_NAME con éxito"
        SUMMARY+="• Respaldo creado exitosamente\n"
        SUMMARY+="• Subido a $CLOUD_NAME con éxito\n"
    else
        echo -e "\033[1;31m  ✗ Error en la subida\033[0m"
        SUMMARY+="• Respaldo creado pero no subido\n"
    fi
fi

# 5. Descarga e instalación
display_message "\n• Descargando versión actualizada..."
if wget -q -O "/usr/bin/astra" "https://satsources.satlink.com.gt/Astra-cesbo/update/astra"; then
    chmod 755 "/usr/bin/astra"
clear

satlink_info

    echo -e "\033[1;34m========================================\033[0m"
    echo -e "\033[1;32m          PROCESO COMPLETADO            \033[0m"
    echo -e "\033[1;34m========================================\033[0m"
    
    echo -e "$SUMMARY"
    echo -e "\033[1;36m• Versión SATLINK instalada\033[0m"
    echo -e "\033[1;36m• Hora finalización: $(date '+%Y-%m-%d %H:%M:%S %Z')\033[0m"
    echo -e "\033[1;34m========================================\033[0m"
else
    clear
    echo -e "\033[1;31m========================================\033[0m"
    echo -e "\033[1;31m       ERROR EN LA ACTUALIZACIÓN         \033[0m"
    echo -e "\033[1;31m========================================\033[0m"
    echo -e "\033[1;33m• No se pudo completar la actualización\033[0m"
    echo -e "\033[1;33m• Contacte a Soporte SATLINK\033[0m"
    echo -e "\033[1;31m========================================\033[0m"
fi

# ==============================================
# CONFIGURACIÓN FINAL DEL SERVICIO
# ==============================================
handle_service enable
handle_service restart
sleep 5s ; echo "" > ~/.bash_history && history -c ; clear
        ;;

        4)

echo -e "┌────── SATLINK MENU INSTALL - https://t.me/Satlink502 ─────┐ "
echo -e "             ${GREEN}Iniciando la descarga...${NC}         "
echo -e "└───────────────────────────────────────────────────────────┘ "

curl -o /etc/astra/astra.conf http://satsources.satlink.com.gt/sat-tools/astra.conf ; systemctl restart astra ; echo "" > ~/.bash_history && history -c ; clear

echo -e "┌────── SATLINK MENU INSTALL - https://t.me/Satlink502 ─────┐ "
echo -e "               ${GREEN}Descarga completada.${NC}           "
echo -e "└───────────────────────────────────────────────────────────┘ "

satlink_info

sleep 3s

        ;;

        5)

bash <(curl -s https://satsources.satlink.com.gt/sat-tools/astra-key.sh)

        ;;

        6)

echo ""
echo "${txtyellow} ┌──────────────────────────────────────┐ "
echo "${txtyellow} │              ACTIVANDO UDP           │ "
echo "${txtyellow} └──────────────────────────────────────┘ "
sed '2s/"_output":/"output":/' /etc/astra/astra.conf ; systemctl restart astra ; echo "" > ~/.bash_history && history -c ; clear


        ;;

        7)

echo ""
echo "${txtyellow} ┌──────────────────────────────────────┐ "
echo "${txtyellow} │          DESINSTALANDO ASTRA         │ "
echo "${txtyellow} └──────────────────────────────────────┘ "

systemctl stop astra ; systemctl disable astra | astra remove ; rm -rf /usr/bin/astra /etc/astra ; rm -rf /lib/systemd/system/astra.service ; cd / ; echo "" > ~/.bash_history && history -c ; clear

        ;;     

        *) ;; # some action on other
    esac
done
clear # clear after user pressed Cancel
