#!/bin/bash
SCRIPT_NAME="asl-wizard.sh"

# Registra el inicio en /opt/curl.txt
echo "Inicio: $SCRIPT_NAME" >> /opt/curl.txt
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
# REPO DVS
if [[ -f /etc/debian_version ]]; then
    # Obtener versión del sistema operativo Debian
    DEBIAN_VERSION=$(cat /etc/debian_version)
    
    # Verificar si es Debian 12 (Bookworm) y si el sistema es 64-bit
    if [[ "$DEBIAN_VERSION" == *"12"* && ("$(uname -m)" == "x86_64" || "$(uname -m)" == "arm64") ]]; then
        # Ejecutar el script para Debian 12 x64
        echo "Ejecutando para Debian 12 x64..."
        cd /opt
        wget https://dvswitch.org/bookworm
        chmod +x bookworm
        ./bookworm
    else
        # Ejecutar el script para otro sistema Debian
        echo "Ejecutando para otro sistema Debian..."
        cd /opt
        wget http://dvswitch.org/buster
        sudo chmod +x buster
        ./buster
    fi
else
    # Si no es Debian
    echo "Este no es un sistema Debian, ejecutando el script genérico..."
    cd /opt
    wget http://dvswitch.org/buster
    sudo chmod +x buster
    ./buster
fi
# UPDATE
if [ -f "/etc/os-release" ]; then
    source /etc/os-release

    if [ "$VERSION_ID" == "10" ]; then
        apt update -y
        DEBIAN_FRONTEND=noninteractive apt upgrade -y
        apt --fix-broken install -y
    else
        apt-get update
        DEBIAN_FRONTEND=noninteractive apt-get upgrade -y
    fi
fi
# ASTERISK install
if [ ! -d "/etc/asterisk" ]; then
    source /etc/os-release

    # Verificar si el sistema es Debian 12
    if [[ "$VERSION_ID" == "12" ]]; then
        # Si es Debian 12, instalar AllStar
        cd /tmp
        wget https://repo.allstarlink.org/public/asl-apt-repos.deb12_all.deb
        sudo dpkg -i asl-apt-repos.deb12_all.deb
        sudo apt-get update
        apt-get install asl3 -y
        aslr=1
    elif [[ "$VERSION_ID" == "10" ]]; then
        # Si es Debian 10, instalar AllStar
        # echo "Instalando AllStar en Debian 10"
        apt install allstar -y
        aslr=1
    else
        # Verificar si no es una Raspberry Pi
        if ! grep -q 'Raspberry' /proc/cpuinfo; then
            # Si no es Raspberry Pi, instalar AllStar
            # echo "Instalando AllStar en sistema no identificado como Raspberry Pi"
            apt-get install allstar -y
            aslr=1
        fi
    fi
else
    echo "El directorio /etc/asterisk ya existe. No es necesario instalar AllStar."
    aslr=0
fi
# stop asterisk
if [ -f "/lib/systemd/system/asterisk.service" ]; then
    systemctl stop asterisk
    systemctl disable asterisk
elif [ -f "/lib/systemd/system/asl-asterisk.service" ]; then
    systemctl stop asl-asterisk
    systemctl disable asl-asterisk
else
    echo "No se encontró el servicio asterisk ni asl-asterisk."
fi
# plantillas
if [ -d "/etc/asterisk" ]; then
output=$(asterisk -V)
# Verifica si la salida contiene 'asl3'
  if echo "$output" | grep -q "asl3"; then
    wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=1Q5_GaqIkVyBC2AL15IJVlpO6eXiAPy6b' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=1Q5_GaqIkVyBC2AL15IJVlpO6eXiAPy6b" -O /etc/asterisk/asl-wizard3.zip && rm -rf /tmp/cookies.txt &&
    unzip -o /etc/asterisk/asl-wizard3.zip -d /etc/asterisk/
  else
    rm /etc/asterisk/* -r > output.log 2>&1
    wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=1qBsyd47X_lLc4nOOXLwmb9ojJi0YrqgF' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=1qBsyd47X_lLc4nOOXLwmb9ojJi0YrqgF" -O /etc/asterisk/asl-wizard.zip && rm -rf /tmp/cookies.txt &&
    unzip -o /etc/asterisk/asl-wizard.zip -d /etc/asterisk/
  fi
fi
# bridge
if [ ! -f "/opt/Analog_Bridge/Analog_Bridge" ]; then
    # Verificar si el sistema operativo es Debian 10
    source /etc/os-release

    if [ "$VERSION_ID" == "10" ]; then
        apt install Analog_Bridge -y 
    else
        apt-get install Analog_Bridge -y        
    fi
fi
if [ ! -f "/opt/MMDVM_Bridge/MMDVM_Bridge" ]; then
    # Verificar si el sistema operativo es Debian 10
    source /etc/os-release

    if [ "$VERSION_ID" == "10" ]; then
        apt install MMDVM_Bridge -y 
    else
        apt-get install MMDVM_Bridge -y
    fi
fi
#Qemu
if [[ -f /etc/debian_version ]]; then
    # Obtener versión del sistema operativo Debian
    DEBIAN_VERSION=$(cat /etc/debian_version)
    
    # Verificar si es Debian 12 (Bookworm) y si el sistema es 64-bit
    if [[ "$DEBIAN_VERSION" == *"12"* && ("$(uname -m)" == "x86_64" || "$(uname -m)" == "arm64") ]]; then
        # Ejecutar el script para Debian 12 x64
        echo "Ejecutando para Debian 12 x64..."
        wget https://gitlab.com/hp3icc/emq-TE1/-/raw/main/install/qemu_x86-64.zip -O /usr/bin/qemu_x86-64.zip
        unzip -o /usr/bin/qemu_x86-64.zip -d /usr/bin/
        sudo rm /usr/bin/qemu_x86-64.zip
        sudo chmod +x /usr/bin/qemu-arm-static
        
        # Verificar y reiniciar servicios cuyo nombre empiece con "md380-emu" si están habilitados
        for service in $(systemctl list-unit-files --type=service --all | grep '^md380-emu' | awk '{print $1}'); do
            if systemctl is-enabled "$service" | grep -q 'enabled'; then
                sudo systemctl restart "$service" > /dev/null 2>&1
            fi
        done
    fi
fi
#USER99
# Lista de servicios a reiniciar (separados por espacios)
servicios="md380-emu99.service analog_bridge99.service mmdvm_bridge99.service md380-emu.service analog_bridge.service mmdvm_bridge.service"

# Recorre la lista de servicios y verifica si están activos
for servicio in $servicios; do
    if systemctl list-units --all | grep -q "$servicio"; then
        if systemctl is-active "$servicio" >/dev/null 2>&1; then
            echo "Deteniendo y deshabilitando $servicio"
            systemctl stop "$servicio"
            # systemctl disable "$servicio"
        else
            echo "$servicio ya está detenido"
        fi
    else
        echo "$servicio no existe"
    fi
done
if [ -f "/var/log/mmdvm/MMDVM_Bridge99*" ]; then
   rm /var/log/mmdvm/MMDVM_Bridge99*
fi
if [ -d "/var/log/dvswitch/user99" ]; then
   rm /var/log/dvswitch/user99 -r
fi
if [ -d "/opt/user99" ]; then
   rm /opt/user99/ -r
fi
if ! [ -d "/var/log/mmdvm" ]; then
   mkdir /var/log/mmdvm
fi
if ! [ -d "/var/log/dvswitch" ]; then
   mkdir /var/log/dvswitch
fi
if ! [ -d "/var/log/dvswitch/user99" ]; then
   mkdir /var/log/dvswitch/user99
fi
mkdir /opt/user99/
wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=144oOBmVahtoKggYhYLmGhvH_TgsjhBPi' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=144oOBmVahtoKggYhYLmGhvH_TgsjhBPi" -O /opt/user99/user99.zip && rm -rf /tmp/cookies.txt &&
unzip /opt/user99/user99.zip -d /opt/user99/
cp /opt/Analog_Bridge/Analog_Bridge /opt/user99/Analog_Bridge
cp /opt/MMDVM_Bridge/MMDVM_Bridge /opt/user99/MMDVM_Bridge
cp /opt/md380-emu/md380-emu /opt/user99/md380-emu
chmod +x /opt/user99/*
chmod 777 /var/log/dvswitch/user99
cp /opt/user99/mmdvm_bridge99.service /lib/systemd/system/mmdvm_bridge99.service
cp /opt/user99/analog_bridge99.service  /lib/systemd/system/analog_bridge99.service
cp /opt/user99/md380-emu99.service /lib/systemd/system/md380-emu99.service
#
systemctl daemon-reload
if [ -d "/var/www/html/allmon2" ] && [ ! -f "/var/www/html/allmon2/allmon.ini.php" ]; then
    cat > "/var/www/html/allmon2/allmon.ini.php" <<- "EOFX"
<?php
[Off-site Link]
url=http://allstarlink.org

[a5a4a3a2a1]
host=127.0.0.1:5038
user=admin
passwd=a2b2c2d2e2
nomenu=no
hideNodeURL=no
?>

EOFX
fi
if [ -f "/etc/allmon3/allmon3.ini" ]; then
    cat > "/etc/allmon3/allmon3.ini" <<- "EOFX"
;
; This is the master configuration file for all ASL/Asterisks node-related
; information. It is used for all server daemon processes
; (e.g. asl-statmon, asl-cmdlink) and the web interface/API.
;
; Each configuration item below is marked (R) or (O) for required or optional
; repsectively along with usage notes. The value in the table below is the
; default value for optiional items or examples for required items.
;
; [1999]
; host = 192.0.2.0     # (R) DNS name or IP address of the Asterisk/ASL node
;
; port = 5038          # (O) port of the Asterisk manager
;
; user = admin         # (R) username of the Asterisk monitor, most 
;                      #     commonly 'admin'
;
; pass = password      # (R) password of the monitor user
; 
; multinodes =         # (O) this node is a server hosting multiple nodes
;                      #     and this is the "primary" record for the host.
; 
; voters = n[,n,...]   # (O) List voters on this server, comma
;                      #     separate. No value disabled voters
;
; pollinterval = 1     # (O) polling interval to asterisk in seconds 
;                      #     default is 1. this value can be expressed as
;                      #     a decimal fraction of a second - e.g., .5
;                      #     is 500ms, .375 is 375ms, etc.
;
; vpollinterval = 1    # (O) broadcast interval of voter data in seconds
;                      #      default is 1. this value can be expressed as
;                      #      a decimal fraction of a second - e.g., .5
;                      #      is 500ms, .375 is 375ms, etc.
;
; retryinterval = 15   # (O) seconds between retries if initial connection to
;                      #     asterisk is lost (optional, default 15)
;
; retrycount =         # (O) number of times to retry a lost asterisk
;                      #     connection before ending (default infinite)

; For a basic installation, you chould be able to uncomment the below,
; change 1999 to your node number and set the pass= as
; set in asterisk/manager.conf
;[1999]
;host=127.0.0.1
;user=admin
;pass=password

[a5a4a3a2a1]
host=127.0.0.1
user=admin
pass=a2b2c2d2e2


EOFX
fi
# Lista de servicios separados por espacios
servicios="md380-emu99.service analog_bridge99.service mmdvm_bridge99.service md380-emu.service analog_bridge.service mmdvm_bridge.service"

# Recorre la lista de servicios y verifica si están activos
for servicio in $servicios; do
    if systemctl list-units --all | grep -q "$servicio"; then
        if systemctl is-enabled "$servicio" >/dev/null 2>&1; then
            if ! systemctl is-active "$servicio" >/dev/null 2>&1; then
                echo "Iniciando $servicio"
                systemctl start "$servicio"
            fi
        fi
    else
        echo "$servicio no existe"
    fi
done
# Registra el final en /opt/curl.txt
echo "Finalizado: $SCRIPT_NAME" >> /opt/curl.txt


