#!/bin/bash

if [ $EUID -ne 0 ]; then
    whiptail --title "sudo su" --msgbox "requiere ser usuario root , escriba (sudo su) antes de entrar a menu / requires root user, type (sudo su) before entering menu" 0 50
    exit 1
fi
# Crear archivo de versión
cat > /opt/emq-ver <<- "EOF"
EMQ-VER:  25.02.02
EOF
# Actualizar la lista de paquetes una vez al principio
apt-get update

# Ejecutar actualización completa
DEBIAN_FRONTEND=noninteractive apt-get full-upgrade -y

# Verificar si es necesario ejecutar autoremove
if apt-get --dry-run autoremove | grep -q "The following packages will be REMOVED:"; then
    echo "Ejecutando autoremove..."
    apt-get autoremove -y
else
    echo "No es necesario ejecutar autoremove."
fi

# Lista de aplicaciones para verificar e instalar
apps="sudo curl git make build-essential libusb-1.0-0-dev python3 python3-pip libi2c-dev i2c-tools lm-sensors wget python3-dev python3-venv libffi-dev libssl-dev cargo pkg-config sed libmariadb-dev zip unzip rrdtool openssl wavemon gcc g++ cmake libasound2-dev libudev-dev gpsd libgps-dev gpsd-clients gpsd-tools chrony libsamplerate0-dev"

# Función para verificar e instalar una aplicación
check_and_install() {
    app=$1
    if ! dpkg -s $app 2>/dev/null | grep -q "Status: install ok installed"; then
        echo "$app no está instalado. Instalando..."
        DEBIAN_FRONTEND=noninteractive apt-get install -y $app || true
        if dpkg -s $app 2>/dev/null | grep -q "Status: install ok installed"; then
            echo "$app instalado correctamente."
        else
            echo "No se pudo instalar $app. Continuando con la siguiente aplicación..."
        fi
    else
        echo "$app ya está instalado."
    fi
}

# Verificar e instalar cada aplicación
for app in $apps; do
    check_and_install $app
done

# Verificar y actualizar python3-venv si no está instalado
if ! dpkg -s python3-venv >/dev/null 2>&1; then
    echo "python3-venv no está instalado. Instalando..."
    apt-get install python3-venv -y
    echo "python3-venv instalado correctamente."
fi

# Crear y activar un entorno virtual
cd /opt/
python3 -m venv myenv
source myenv/bin/activate

# Instalar pip en el entorno virtual
if [ -f "/opt/get-pip.py" ]; then
    rm /opt/get-pip.*
fi
wget https://bootstrap.pypa.io/pip/get-pip.py
python3 get-pip.py
rm get-pip.*

# Instalar paquetes en el entorno virtual
apt-get install -y libssl-dev

python3 -m pip install pip setuptools
python3 -m pip install cryptography Twisted bitstring MarkupSafe bitarray configparser aprslib attrs wheel service_identity pyOpenSSL mysqlclient tinydb ansi2html mysql-connector-python pandas xlsxwriter cursor pynmea2 maidenhead flask folium mysql-connector resettabletimer setproctitle requests libscrc Pyro5 dmr_utils3 spyne autobahn jinja2 service-identity

# Desactivar el entorno virtual
deactivate

# Instalar Rust y configurar versión
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
source $HOME/.cargo/env

rustup install 1.72.0
rustup default 1.72.0

# Detectar el sistema operativo y su versión
if [ -f "/etc/os-release" ]; then
    . /etc/os-release
    OS=$ID
    VERSION=$VERSION_ID
else
    echo "No se pudo detectar el sistema operativo."
    exit 1
fi
# Instalación de módulos pip según el sistema operativo
if [ "$OS" == "debian" ] && [ "$VERSION" == "12" ]; then
    /usr/bin/python3 -m pip install --break-system-packages pyOpenSSL autobahn jinja2 dmr-utils3 ansi2html aprslib tinydb mysqlclient setproctitle pynmea2 maidenhead Twisted spyne Pyro5 bitstring bitarray dmr_utils3 configparser resettabletimer setuptools wheel MarkupSafe service-identity
    source myenv/bin/activate
    /usr/bin/python3 -m pip uninstall --break-system-packages twisted -y
    /usr/bin/python3 -m pip install --break-system-packages twisted==22.10.0
    deactivate
else
    /usr/bin/python3 -m pip install --upgrade pyOpenSSL autobahn jinja2 dmr-utils3 ansi2html aprslib tinydb mysqlclient setproctitle pynmea2 maidenhead Twisted spyne Pyro5 bitstring bitarray dmr_utils3 configparser resettabletimer setuptools wheel MarkupSafe service-identity
    sudo pip3 uninstall -y twisted --quiet
    pip install Twisted==22.10.0
fi

echo "Instalación completa."

# Configuración adicional (timezone, cron, etc.)
sudo timedatectl set-timezone America/Panama

# Crear script para editar cronjobs
cat > /usr/local/bin/cronedit.sh <<- "EOF"
cronjob_editor () {
# usage: cronjob_editor '<interval>' '<command>' <add|remove>

if [[ -z "$1" ]] ;then printf " no interval specified\n" ;fi
if [[ -z "$2" ]] ;then printf " no command specified\n" ;fi
if [[ -z "$3" ]] ;then printf " no action specified\n" ;fi

if [[ "$3" == add ]] ;then
    # add cronjob, no duplication:
    ( sudo crontab -l | grep -v -F -w "$2" ; echo "$1 $2" ) | sudo crontab -
elif [[ "$3" == remove ]] ;then
    # remove cronjob:
    ( sudo crontab -l | grep -v -F -w "$2" ) | sudo crontab -
fi
}
cronjob_editor "$1" "$2" "$3"
EOF
sudo chmod +x /usr/local/bin/cronedit.sh

# Limpiar archivos temporales
if [ -f "/opt/curl.txt" ]; then
    rm /opt/curl.txt
fi
if [ -f "/opt/curl-final.txt" ]; then
    rm /opt/curl-final.txt
fi
# Ejecutar scripts de instalación adicionales
echo "Iniciando instalación de scripts adicionales..."
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/install/ipv6off.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/install/rpiswap.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/install/rm.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/install/dvswitch.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/install/direwolf.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/install/ysfreflector.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/install/mmdvm.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/install/ysfgateway2.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/install/gotty.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/install/noip.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/python-aprs-beacon/-/raw/main/install.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/install/rebooters.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/install/ysf2dmr.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/install/dmrgw.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/install/f2b+ufw.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/python-aprs-wx/-/raw/main/install.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/install/ysf2ysf.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/easy-hbl/-/raw/main/hbl.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/easy-hbl/-/raw/main/hbljson.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/install/fdmr.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/install/nxdn2dmr.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/install/p25.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/install/p25cross.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/install/asl-wizard.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/install/nginx.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/install/allmon3.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/install/xlxd.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/menu/data-mmdvm.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/install/n-manager.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/install/wifi-connect.sh)"
#
echo "Instalación de menús..."
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/menu/menu-aprs)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/python-aprs-beacon/-/raw/main/menu.sh)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/menu/menu-dvs)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/menu/menu-dw)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/menu/menu-fdmr)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/menu/menu-mmdvm)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/menu/menu-noip)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/menu/menu-reboot)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/menu/menu-web)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/menu/menu-ysf)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/menu/menu-ysf2dmr)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/menu/menu-ufw)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/menu/menu-ysf2ysf)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/menu/menu-nxdn2dmr)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/menu/menu-p25r)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/menu/menu-wifi-manager)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/menu/menu-asl)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/menu/menu-xlx)" &&
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/menu/menu-ip)"

# Configuración adicional para Raspberry Pi
bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/install/raspberry.sh)"

# Habilitar servicio gotty
sudo systemctl enable gotty.service

# Ajustar configuración de Jitter
find /opt/ -type f -exec sed -i "s|Jitter=.*|Jitter=240|g" {} +

bash -c "$(curl -fsSLk https://gitlab.com/hp3icc/emq-TE1/-/raw/main/menu/menu)"
# Crear script de finalización
variable22=$(grep "EMQ-VER:" /opt/emq-ver | grep -Eo '[A.0-9]{1,9}')
whiptail --title "emq-TE1+ Rev: $variable22" --msgbox "Instalacion finalizada / Installation completed:\n\n\
El equipo requiere reinicia, ingrece nuevamente y escriba menu\n\
The computer requires a restart, enter again and type menu" 0 50
history -c && history -w
sudo reboot