#!/bin/bash
cat > /bin/menu-asl <<- "EOF"
#!/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
if ! [ -d "/etc/asterisk" ]; then
  whiptail --title "Easy-ASL" --msgbox "AllStarLink not Found / AllStarLink no instalado" 0 50
  exit 0
fi
while : ; do
choix=$(whiptail --title "Script Proyect HP3ICC Menu AllStarLink" --menu "Suba o Baje con las flechas del teclado y seleccione el numero de opcion" 15 50 5 \
1 " Easy ASL-Config Echolink  " \
2 " Easy ASL-Bridge-DMR  " \
3 " asl-menu  " \
4 " Menu Principal " 3>&1 1>&2 2>&3)
exitstatus=$?

if [ $exitstatus = 0 ]; then
    echo "Your chosen option:" $choix
else
    echo "You chose cancel."
    break
fi

case $choix in
1)
menu-asle
 ;;
2)
menu-aslb
 ;;
3)
asl-menu
 ;;
4)
break
 ;;
esac
done
exit 0
EOF
if [ -d "/etc/nginx" ]; then
cat > /bin/menu-asl <<- "EOF"
#!/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
if ! [ -d "/etc/asterisk" ]; then
  whiptail --title "Easy-ASL" --msgbox "AllStarLink not Found / AllStarLink no instalado" 0 50
  exit 0
fi
while : ; do
choix=$(whiptail --title "Script Proyect HP3ICC Menu AllStarLink" --menu "Suba o Baje con las flechas del teclado y seleccione el numero de opcion" 15 50 6 \
1 " Easy ASL-Config Echolink  " \
2 " Easy ASL-Bridge-DMR  " \
3 " Dashboard Allmon3  " \
4 " asl-menu  " \
5 " Menu Principal " 3>&1 1>&2 2>&3)
exitstatus=$?

if [ $exitstatus = 0 ]; then
    echo "Your chosen option:" $choix
else
    echo "You chose cancel."
    break
fi

case $choix in
1)
menu-asle
 ;;
2)
menu-aslb
 ;;
3)
menu-allmon3
 ;;
4)
asl-menu
 ;;
5)
break
    ;;
esac
done
exit 0
EOF
cat > /bin/menu-allmon3 <<- "EOFA"
#!/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
if ! [ -d "/etc/asterisk" ]; then
  whiptail --title "Easy-ASL" --msgbox "AllStarLink not Found / AllStarLink no instalado" 0 50
  exit 0
fi
while : ; do
choix=$(whiptail --title "Script Proyect HP3ICC Menu AllMon3" --menu "Suba o Baje con las flechas del teclado y seleccione el numero de opcion" 15 50 9 \
1 " Setup Port http & dns Dashboard " \
2 " Start Dashboard Allmon3  " \
3 " Stop Dashboard Allmon3   " \
4 " edit allmon3.ini  " \
5 " edit web.ini  " \
6 " edit menu.ini  " \
7 " set password login  " \
8 " Menu Principal " 3>&1 1>&2 2>&3)
exitstatus=$?

if [ $exitstatus = 0 ]; then
    echo "Your chosen option:" $choix
else
    echo "You chose cancel."
    break
fi

case $choix in
1)
wdp=/opt/wdp9
if [ -f "/tmp/w0dn0.txt" ]; then
    rm /tmp/w0dn0.txt
fi
if [ -f "/tmp/wd0p.txt" ]; then
    rm /tmp/wd0p.txt
fi
if [ -f "/etc/nginx/sites-enabled/allmon3" ]; then
rm /etc/nginx/sites-enabled/allmon3
fi
if [ -f "/etc/nginx/sites-enabled/000" ]; then
    rm /etc/nginx/sites-enabled/000
fi
sudo systemctl restart nginx

    whiptail --title "Setup Webserver" --inputbox "Select HTTP port:" 10 60 2>/tmp/wd0p.txt
    exitstatus=$?
    
    if [ $exitstatus != 0 ]; then
        echo "You chose cancel. Exiting..."
        exit 1  # Salir del script con un código de error
    fi
    
    wd0p=$(cat /tmp/wd0p.txt)
    
    whiptail --title "Setup Webserver" --inputbox "DNS name:" 10 60 2>/tmp/w0dn0.txt
    exitstatus=$?
    
    if [ $exitstatus != 0 ]; then
        echo "You chose cancel. Exiting..."
        exit 1  # Salir del script con un código de error
    fi
    
    w0dn0=$(cat /tmp/w0dn0.txt)
    
cat > "/etc/allmon3/allmon3.ini" <<- "EOF"
;
; 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


EOF
sed -i "s|Web-Dashboar-Port:.*|Web-Dashboar-Port: $wd0p|g" $wdp
sed -i "s|Web-Dashboar-dns:.*|Web-Dashboar-dns: $w0dn0|g" $wdp
wd0p=$(grep "Web-Dashboar-Port:" $wdp | grep -oP 'Web-Dashboar-Port:\s*\K.*')
if [ -z "$wd0p" ]
then wd0p=80

fi
w0dn0=$(grep "Web-Dashboar-dns:" $wdp | grep -oP 'Web-Dashboar-dns:\s*\K.*')
ASL_N=$(grep "AllStartLink-node:" $wdp | grep -oP 'AllStartLink-node:\s*\K.*')
    if [ -z "$w0dn0" ]; then
        if sudo netstat -tuln | grep -q "0.0.0.0:$wd0p "; then
            whiptail --title "Check Port" --msgbox "El puerto $wd0p está ocupado. The port $wd0p is busy" 0 50
            exit 0
          else
            echo ""
        fi
    fi
 sudo ln -sf /etc/nginx/sites-available/allmon3 /etc/nginx/sites-enabled/allmon3
if [ ! -z "$w0dn0" ]; then
    sudo sed -i '3i\    server_name w0dn0;' /etc/nginx/sites-enabled/allmon3
fi
sed -i "14s|.*|Location=ASL${ASL_N} <> DMR|" /opt/user99/MMDVM_Bridge.ini
sed -i "s|wd0p|$wd0p|g" /etc/nginx/sites-enabled/allmon3
sed -i "s|w0dn0|$w0dn0|g" /etc/nginx/sites-enabled/allmon3

if [ -f "/etc/nginx/sites-enabled/000" ]; then
    rm /etc/nginx/sites-enabled/000
fi
asln=$(grep "astnode =" /etc/asterisk/echolink.conf | grep -oP 'astnode =\s*\K.*')
asld=$(grep "secret =" /etc/asterisk/manager.conf | grep -oP 'secret =\s*\K.*')
sed -i "s|a5a4a3a2a1|$asln|g; s|a2b2c2d2e2|$asld|g" /etc/allmon3/allmon3.ini 
sudo systemctl restart nginx
# Lista de servicios a reiniciar
servicios="allmon3"

# Primero, detener todos los servicios
for servicio in $servicios; do
    if systemctl is-enabled "$servicio" &>/dev/null || systemctl is-active "$servicio" &>/dev/null; then
        echo "Deteniendo $servicio"
        sudo systemctl stop "$servicio"
    fi
done

# Esperar un momento para asegurarse de que todos los servicios se detengan completamente
sleep 5

# Luego, iniciar todos los servicios
for servicio in $servicios; do
    echo "Iniciando $servicio"
    sudo systemctl start "$servicio"
    sudo systemctl enable "$servicio" &>/dev/null
done
 ;;
2)
cat > "/etc/allmon3/allmon3.ini" <<- "EOF"
;
; 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


EOF
wdp=/opt/wdp9
if [ -f "/etc/nginx/sites-enabled/allmon3" ]; then
rm /etc/nginx/sites-enabled/allmon3
fi
if [ -f "/etc/nginx/sites-enabled/000" ]; then
    rm /etc/nginx/sites-enabled/000
fi
sudo systemctl restart nginx

wd0p=$(grep "Web-Dashboar-Port:" $wdp | grep -oP 'Web-Dashboar-Port:\s*\K.*')
if [ -z "$wd0p" ]
then wd0p=80

fi
w0dn0=$(grep "Web-Dashboar-dns:" $wdp | grep -oP 'Web-Dashboar-dns:\s*\K.*')
    if [ -z "$w0dn0" ]; then
        if sudo netstat -tuln | grep -q "0.0.0.0:$wd0p "; then
            whiptail --title "Check Port" --msgbox "El puerto $wd0p está ocupado. The port $wd0p is busy" 0 50
            exit 0
          else
            echo ""
        fi
    fi
 sudo ln -sf /etc/nginx/sites-available/allmon3 /etc/nginx/sites-enabled/allmon3
if [ ! -z "$w0dn0" ]; then
    sudo sed -i '3i\    server_name w0dn0;' /etc/nginx/sites-enabled/allmon3
fi 
sed -i "s|wd0p|$wd0p|g" /etc/nginx/sites-enabled/allmon3
sed -i "s|w0dn0|$w0dn0|g" /etc/nginx/sites-enabled/allmon3

if [ -f "/etc/nginx/sites-enabled/000" ]; then
    rm /etc/nginx/sites-enabled/000
fi
asln=$(grep "astnode =" /etc/asterisk/echolink.conf | grep -oP 'astnode =\s*\K.*')
asld=$(grep "secret =" /etc/asterisk/manager.conf | grep -oP 'secret =\s*\K.*')
sed -i "s|a5a4a3a2a1|$asln|g; s|a2b2c2d2e2|$asld|g" /etc/allmon3/allmon3.ini
sudo systemctl restart nginx
# Lista de servicios a reiniciar
servicios="allmon3"

# Primero, detener todos los servicios
for servicio in $servicios; do
    if systemctl is-enabled "$servicio" &>/dev/null || systemctl is-active "$servicio" &>/dev/null; then
        echo "Deteniendo $servicio"
        sudo systemctl stop "$servicio"
    fi
done

# Esperar un momento para asegurarse de que todos los servicios se detengan completamente
sleep 5

# Luego, iniciar todos los servicios
for servicio in $servicios; do
    echo "Iniciando $servicio"
    sudo systemctl start "$servicio"
    sudo systemctl enable "$servicio" &>/dev/null
done
 ;;
3)
if [ -f "/etc/nginx/sites-enabled/allmon3" ]; then
rm /etc/nginx/sites-enabled/allmon3
fi
if [ -f "/etc/nginx/sites-enabled/000" ]; then
    rm /etc/nginx/sites-enabled/000
fi
sudo systemctl restart nginx
# Lista de servicios a reiniciar
servicios="allmon3"
# Recorre la lista de servicios y verifica si están activos
for servicio in "${servicios[@]}"; do
    if systemctl is-enabled "$servicio" &>/dev/null || systemctl is-active "$servicio" &>/dev/null; then
        echo "stop $servicio"
        sudo systemctl disable "$servicio"
        sudo systemctl stop "$servicio"
    fi
done
 ;;
4)
nano /etc/allmon3/allmon3.ini
if systemctl is-active "allmon3" >/dev/null 2>&1; then
 systemctl restart allmon3
fi
 ;;
5)
nano /etc/allmon3/web.ini
if systemctl is-active "allmon3" >/dev/null 2>&1; then
 systemctl restart allmon3
fi
 ;;
6)
nano /etc/allmon3/menu.ini
if systemctl is-active "allmon3" >/dev/null 2>&1; then
 systemctl restart allmon3
fi
 ;;
7)
allmon3-passwd allmon3
# Lista de servicios a reiniciar
servicios="allmon3"

# Primero, detener todos los servicios
for servicio in $servicios; do
    if systemctl is-enabled "$servicio" &>/dev/null || systemctl is-active "$servicio" &>/dev/null; then
        echo "Deteniendo $servicio"
        sudo systemctl stop "$servicio"
    fi
done

# Esperar un momento para asegurarse de que todos los servicios se detengan completamente
sleep 5

# Luego, iniciar todos los servicios
for servicio in $servicios; do
    echo "Iniciando $servicio"
    sudo systemctl start "$servicio"
    sudo systemctl enable "$servicio" &>/dev/null
done
 ;;
8)
break
 ;;
esac
done
exit 0
EOFA
fi
if [ ! -f "/opt/wdp9" ]; then
cat > /opt/wdp9 <<- "EOFX"
#########################################
# Select number port, allmon3 Dashboard #
#########################################

Web-Dashboar-Port:  80
Web-Dashboar-dns:


EOFX
fi
if [ -d "/etc/allmon3" ]; then
cat > /etc/allmon3/menu.ini <<- "EOF"
;
; menu.ini.example
;
; If this file is present in the api/ subdirectory of Allmon3's web interface
; and named menu.ini, this file will override the default behavior of the
; web interface simply listing the configured nodes in the left navbar.
; If this file is not present, all nodes in allmon3.ini/allmon3.ini.php
; will display singly in configured order.
;
; NOTE: Not listing a node in the menu WILL NOT cause the node to go
; un-polled if it is already configured in allmon3.ini. This allows
; the system administrator to have "hidden" nodes. If you want to completely
; stop polling an Asterisk/ASL node, the node must be removed from allmon3.ini.
;
; The format for this file is as follows:
;
; [ TITLE ]                         :: The stanza header is the label
;                                   :: for this menu item
;
; type  = ( menu | single )         :: If type = menu, the item is interpreted as a dropdown
;                                   :: menu with each LABEL item displaying. If the
;                                   :: type = single, then only a the first LABEL = TARGET
;                                   :: will be displayed as a non-dropdown. In the case of
;                                   :: type = single, the [ TITLE ] is ignored completely
;
; LABEL = TARGET                    :: Each [ TITLE ] displays one or more LABELS
; LABEL = TARGET                    :: with a link to TARGET. When TARGET is all numbers
; LABEL = TARGET                    :: then TARGET is assumed to be a ASL node and
;                                   :: the link will filter down to the TARGET node
;                                   :: specified. Any other pattern will be interpreted
;                                   :: as a full or partial URL/URI.
;                                   ::
;                                   :: Of special node, creating a menu item of
;                                   :: multiple nodes to display, TARGET and simply be
;                                   :: #NODE,NODE,NODE - e.g. #1999,1998,1997
;
; Note that the order of the nodes within a stanza is irrelevant. They will be displayed
; as sorted alphabestically ascending according to UTF-8 (e.g. 0-9, A-Z, +).
;
; Here's an example menu
;   [ W8WKY ]
;   type = menu
;   W8WKY = 43211
;   48496 = 48496
;   45839 = 45839
;   
;   [ N8XPK ]
;   type = menu
;   N8XPK = 42993
;   43118 = 43118
;   47987 = 47987
;        AllStarLink = https://www.allstarlink.org
;   Blog = http://hp3link.ddns.net
;   
    [ Allstar ]
    type = single
    AllStarLink = https://www.allstarlink.org
;   AllMon3 = https://community.allstarlink.org/t/announcing-a-new-allmon/20067
;   
;   

EOF
fi
if [ -d "/etc/asterisk" ]; then
cat > /bin/menu-asle <<- "EOF"
#!/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
if ! [ -d "/etc/asterisk" ]; then
  whiptail --title "Easy-ASL" --msgbox "AllStarLink not Found / AllStarLink no instalado" 0 50
  exit 0
fi
while : ; do
choix=$(whiptail --title "Script Proyect HP3ICC Menu ASL-Config Echolink" --menu "Suba o Baje con las flechas del teclado y seleccione el numero de opcion" 20 55 10 \
1 " Easy Setup ASL-Config Echolink " \
2 " Iniciar AllStarLink  " \
3 " Detener AllStarLink  " \
4 " Edit echolink.conf  " \
5 " Edit rpt.conf  " \
6 " Edit iax.conf  " \
7 " Edit manager.conf  " \
8 " Restore defauld ASL-Config Echolink " \
9 " Menu Principal " 3>&1 1>&2 2>&3)
exitstatus=$?

if [ $exitstatus = 0 ]; then
    echo "Your chosen option:" $choix
else
    echo "You chose cancel."
    break
fi

case $choix in
1)
    whiptail --title "Easy setup AllStarLink" --inputbox "Echolink Calsign:" 10 60 2>/tmp/echoc.txt
            exitstatus=$?
        if [ $exitstatus != 0 ]; then
            echo "You chose cancel. Exiting..."
            exit 1  # Salir del script con un código de error
        fi
    echoc=$(cat /tmp/echoc.txt)
    echoc=$(echo "$echoc" | tr '[:lower:]' '[:upper:]')
    whiptail --title "Easy setup AllStarLink" --inputbox "Echolink Password:" 10 60 2>/tmp/echop.txt
            exitstatus=$?
        if [ $exitstatus != 0 ]; then
            echo "You chose cancel. Exiting..."
            exit 1  # Salir del script con un código de error
        fi
    echop=$(cat /tmp/echop.txt)
    whiptail --title "Easy setup AllStarLink" --inputbox "Echolink Name:" 10 60 2>/tmp/echon.txt
            exitstatus=$?
        if [ $exitstatus != 0 ]; then
            echo "You chose cancel. Exiting..."
            exit 1  # Salir del script con un código de error
        fi
    echon=$(cat /tmp/echon.txt)
    whiptail --title "Easy setup AllStarLink" --inputbox "Echolink Qth:" 10 60 2>/tmp/echoq.txt
            exitstatus=$?
        if [ $exitstatus != 0 ]; then
            echo "You chose cancel. Exiting..."
            exit 1  # Salir del script con un código de error
        fi
    echoq=$(cat /tmp/echoq.txt)
    whiptail --title "Easy setup AllStarLink" --inputbox "Echolink email:" 10 60 2>/tmp/echoe.txt
            exitstatus=$?
        if [ $exitstatus != 0 ]; then
            echo "You chose cancel. Exiting..."
            exit 1  # Salir del script con un código de error
        fi
    echoe=$(cat /tmp/echoe.txt)
    whiptail --title "Easy setup AllStarLink" --inputbox "Echolink Node Number:" 10 60 2>/tmp/echox.txt
            exitstatus=$?
        if [ $exitstatus != 0 ]; then
            echo "You chose cancel. Exiting..."
            exit 1  # Salir del script con un código de error
        fi
    echox=$(cat /tmp/echox.txt)
    whiptail --title "Easy setup AllStarLink" --inputbox "Allstartlink Node Number:" 10 60 2>/tmp/asln.txt
            exitstatus=$?
        if [ $exitstatus != 0 ]; then
            echo "You chose cancel. Exiting..."
            exit 1  # Salir del script con un código de error
        fi
    asln=$(cat /tmp/asln.txt)
    whiptail --title "Easy setup AllStarLink" --inputbox "Allstartlink Node Password:" 10 60 2>/tmp/aslk.txt
            exitstatus=$?
        if [ $exitstatus != 0 ]; then
            echo "You chose cancel. Exiting..."
            exit 1  # Salir del script con un código de error
        fi
    aslk=$(cat /tmp/aslk.txt)
    whiptail --title "Easy setup AllStarLink" --inputbox "AllMon web manage Password:" 10 60 2>/tmp/asld.txt
            exitstatus=$?
        if [ $exitstatus != 0 ]; then
            echo "You chose cancel. Exiting..."
            exit 1  # Salir del script con un código de error
        fi
    asld=$(cat /tmp/asld.txt)
 if [ -f "/lib/systemd/system/asterisk.service" ]; then
   systemctl stop asterisk
   systemctl disable asterisk
 fi
 if [ -f "/lib/systemd/system/asl-asterisk.service" ]; then
   systemctl stop asl-asterisk
   systemctl disable asl-asterisk
 fi
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
 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
#allstar
sed -i "7s|.*|AllStartLink-node: ${asln}|" /opt/wdp9
sed -i "s|secret =.*|secret = $asld|g" /etc/asterisk/manager.conf
find /etc/asterisk/ -type f -exec sed -i "s|a5a4a3a2a1|$asln|g" {} +             #node allstarlink
find /etc/asterisk/ -type f -exec sed -i "s|a1b1c1d1e1|$aslk|g" {} +             #key allstarlink
find /etc/asterisk/ -type f -exec sed -i "s|a2b2c2d2e2|$asld|g" {} +             #allstar dashboard key
find /etc/asterisk/ -type f -exec sed -i "s|a3b3c3d3e3|$echoc|g" {} +             #callsign
# Crear archivos temporales
touch "/etc/asterisk/simpleusb_tune_usb_${asln}.conf"
touch "/etc/asterisk/usbradio_tune_usb_${asln}.conf"
#
# Configuración de Echolink
#sed -i "s|call =.*|call = $echoc|g" /etc/asterisk/echolink.conf
sed -i "s|pwd =.*|pwd = $echop|g" /etc/asterisk/echolink.conf
sed -i "s|name =.*|name = $echon|g" /etc/asterisk/echolink.conf
sed -i "s|qth =.*|qth = $echoq|g" /etc/asterisk/echolink.conf
sed -i "s|email =.*|email = $echoe|g" /etc/asterisk/echolink.conf
sed -i "s|node =.*|node = $echox|g" /etc/asterisk/echolink.conf
sed -i "s|astnode =.*|astnode = $asln|g" /etc/asterisk/echolink.conf
#
 if [ -d "/var/www/html/allmon2" ]; then
    sed -i "s|a5a4a3a2a1|$asln|g; s|a2b2c2d2e2|$asld|g" /var/www/html/allmon2/allmon.ini.php
 fi
 if [ -f "/etc/allmon3/allmon3.ini" ]; then
    sed -i "s|a5a4a3a2a1|$asln|g; s|a2b2c2d2e2|$asld|g" /etc/allmon3/allmon3.ini
 fi
#
 if [ -f "/lib/systemd/system/asterisk.service" ]; then
   systemctl stop asterisk &&
   systemctl start asterisk
   systemctl enable asterisk
 fi
 if [ -f "/lib/systemd/system/asl-asterisk.service" ]; then
   systemctl stop asl-asterisk &&
   systemctl start asl-asterisk
   systemctl enable asl-asterisk
 fi
  if [ -f "/lib/systemd/system/allmon3.service" ]; then
   systemctl stop allmon3 &&
   systemctl start allmon3
   systemctl enable allmon3
 fi
 ;;
2)
 if [ -f "/lib/systemd/system/asterisk.service" ]; then
   systemctl stop asterisk &&
   systemctl start asterisk
   systemctl enable asterisk
 fi
 if [ -f "/lib/systemd/system/asl-asterisk.service" ]; then
   systemctl stop asl-asterisk &&
   systemctl start asl-asterisk
   systemctl enable asl-asterisk
 fi
   if [ -f "/lib/systemd/system/allmon3.service" ]; then
   systemctl stop allmon3 &&
   systemctl start allmon3
   systemctl enable allmon3
 fi
   ;;
3)
 if [ -f "/lib/systemd/system/asterisk.service" ]; then
   systemctl stop asterisk
   systemctl disable asterisk
 fi
 if [ -f "/lib/systemd/system/asl-asterisk.service" ]; then
   systemctl stop asl-asterisk
   systemctl disable asl-asterisk
 fi
   if [ -f "/lib/systemd/system/allmon3.service" ]; then
   systemctl stop allmon3 &&
   systemctl disable allmon3
 fi
  ;;
4)
nano /etc/asterisk/echolink.conf
 ;;
5)
nano /etc/asterisk/rpt.conf
 ;;
6)
nano /etc/asterisk/iax.conf 
 ;;
7)
nano /etc/asterisk/manager.conf
 ;;
8)
 if [ -f "/lib/systemd/system/asterisk.service" ]; then
   systemctl stop asterisk
   systemctl disable asterisk
 fi
 if [ -f "/lib/systemd/system/asl-asterisk.service" ]; then
   systemctl stop asl-asterisk
   systemctl disable asl-asterisk
 fi
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
 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 [ -d "/etc/allmon3" ]; 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
 ;;
9)
break
    ;;
esac
done
exit 0
EOF
fi
#############################################################
if [ -d "/opt/user99" ]; then
cat > /bin/menu-aslb <<- "EOF"
#!/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
if ! [ -d "/etc/asterisk" ]; then
  whiptail --title "Easy-ASL" --msgbox "AllStarLink not Found / AllStarLink no instalado" 0 50
  exit 0
fi
while : ; do
choix=$(whiptail --title "Script Proyect HP3ICC Menu ASL-Bridge-DMR" --menu "Suba o Baje con las flechas del teclado y seleccione el numero de opcion" 20 50 11 \
1 " Easy setup ASLBridge DMR" \
2 " Iniciar Bridge  " \
3 " Detener Bridge  " \
4 " Config MMDVM_bridge.ini " \
5 " Restore Defauld " \
6 " Menu Principal " 3>&1 1>&2 2>&3)
exitstatus=$?

if [ $exitstatus = 0 ]; then
    echo "Your chosen option:" $choix
else
    echo "You chose cancel."
    break
fi

case $choix in
1)
# Lista de servicios a reiniciar
# Lista de servicios
servicios="mmdvm_bridge99.service analog_bridge99.service md380-emu99.service"

# Recorre la lista de servicios y verifica si están activos
for servicio in $servicios; do
    # Verifica si el servicio está activo y habilitado
    if systemctl is-enabled "$servicio" &>/dev/null || systemctl is-active "$servicio" &>/dev/null; then
        echo "Deteniendo y deshabilitando $servicio"
        systemctl disable "$servicio"
        systemctl stop "$servicio"
    fi
done
    mcall=""
    mid=""
    did=""
    midg=""
    sbridge=""
    txtg=""
    sport=""
    spass=""
    sopti=""
    whiptail --title "Easy setup ASL-Bridge-DMR" --inputbox "Calsign:" 10 60 2>/tmp/mcall.txt
            exitstatus=$?
        if [ $exitstatus != 0 ]; then
            echo "You chose cancel. Exiting..."
            exit 1  # Salir del script con un código de error
        fi
    mcall=$(cat /tmp/mcall.txt)
    mcall=$(echo "$mcall" | tr '[:lower:]' '[:upper:]')
    whiptail --title "Easy setup ASL-Bridge-DMR" --inputbox "DMRId:" 10 60 2>/tmp/mid.txt
            exitstatus=$?
        if [ $exitstatus != 0 ]; then
            echo "You chose cancel. Exiting..."
            exit 1  # Salir del script con un código de error
        fi
    mid=$(cat /tmp/mid.txt)
    whiptail --title "Easy setup ASL-Bridge-DMR" --inputbox "Device ID:  01-99" 10 60 2>/tmp/did.txt
            exitstatus=$?
        if [ $exitstatus != 0 ]; then
            echo "You chose cancel. Exiting..."
            exit 1  # Salir del script con un código de error
        fi
    did=$(cat /tmp/did.txt)
      whiptail --title "Easy setup ASL-Bridge-DMR" --inputbox "IP or dns server DMR:" 10 60 2>/tmp/sbridge=.txt
            exitstatus=$?
        if [ $exitstatus != 0 ]; then
            echo "You chose cancel. Exiting..."
            exit 1  # Salir del script con un código de error
        fi
    sbridge=$(cat /tmp/sbridge=.txt)
    whiptail --title "Easy set=up ASL-Bridge-DMR" --inputbox "Port server DMR:" 10 60 2>/tmp/sport.txt
            exitstatus=$?
        if [ $exitstatus != 0 ]; then
            echo "You chose cancel. Exiting..."
            exit 1  # Salir del script con un código de error
        fi
    sport=$(cat /tmp/sport.txt)
    whiptail --title "Easy setup ASL-Bridge-DMR" --inputbox "Password server DMR:" 10 60 2>/tmp/spass.txt
            exitstatus=$?
        if [ $exitstatus != 0 ]; then
            echo "You chose cancel. Exiting..."
            exit 1  # Salir del script con un código de error
        fi
    spass=$(cat /tmp/spass.txt)
    whiptail --title "Easy setup ASL-Bridge-DMR" --inputbox "TalkGroup / tg sample: 91" 10 60 2>/tmp/txtg.txt
            exitstatus=$?
        if [ $exitstatus != 0 ]; then
            echo "You chose cancel. Exiting..."
            exit 1  # Salir del script con un código de error
        fi
    txtg=$(cat /tmp/txtg.txt)
    whiptail --title "Easy setup ASL-Bridge-DMR" --inputbox "Line Options / sample: TS2=91; " 10 60 2>/tmp/sopti.txt
            exitstatus=$?
        if [ $exitstatus != 0 ]; then
            echo "You chose cancel. Exiting..."
            exit 1  # Salir del script con un código de error
        fi
    sopti=$(cat /tmp/sopti.txt)

        # Modify the MMDVM_Bridge.ini file for DMR
    wdp=/opt/wdp9
    ASL_N=$(grep "AllStartLink-node:" $wdp | grep -oP 'AllStartLink-node:\s*\K.*')
    sed -i "14s|.*|Location=ASL${ASL_N} <> DMR|" /opt/user99/MMDVM_Bridge.ini
    sed -i "3s/Id=.*/Id=${mid}${did}/" /opt/user99/MMDVM_Bridge.ini
    sed -i "69s/Enable=.*/Enable=1/" /opt/user99/MMDVM_Bridge.ini
    sed -i "84s/Enable=.*/Enable=0/" /opt/user99/MMDVM_Bridge.ini
    sed -i "44s/Enable=.*/Enable=1/" /opt/user99/MMDVM_Bridge.ini
    sed -i "50s/Enable=.*/Enable=0/" /opt/user99/MMDVM_Bridge.ini

    sed -i "s/gatewayDmrId =.*/gatewayDmrId = ${mid}/g" /opt/user99/Analog_Bridge.ini
    sed -i "s/repeaterID =.*/repeaterID = ${mid}${did}/" /opt/user99/Analog_Bridge.ini
    sed -i "s/txTg =.*/txTg = ${txtg}/g" /opt/user99/Analog_Bridge.ini

    sed -i "2s/Callsign=.*/Callsign=$mcall/g" /opt/user99/MMDVM_Bridge.ini
    sed -i "70s/Address=.*/Address=$sbridge/g" /opt/user99/MMDVM_Bridge.ini
    sed -i "71s/Port=.*/Port=$sport/g" /opt/user99/MMDVM_Bridge.ini
    sed -i "74s/Password=.*/Password=$spass/g" /opt/user99/MMDVM_Bridge.ini
    sed -i "77s/Options=.*/Options=$sopti/g" /opt/user99/MMDVM_Bridge.ini

    rm -f /tmp/mcall.txt /tmp/mid.txt /tmp/sbridge.txt /tmp/sport.txt /tmp/sopti.txt /tmp/midg.txt /tmp/spass.txt /tmp/did.txt

# Lista de servicios a reiniciar
# Lista de servicios (sin usar paréntesis)
servicios="mmdvm_bridge99.service analog_bridge99.service md380-emu99.service"

# Función para manejar el servicio
manejar_servicio() {
    local servicio="$1"
    if systemctl is-active --quiet "$servicio"; then
        echo "Reiniciando $servicio"
        systemctl restart "$servicio"
    else
        echo "Iniciando y habilitando $servicio"
        systemctl start "$servicio"
        systemctl enable --now "$servicio"  # Habilita e inicia el servicio en un solo comando
    fi
}

# Recorre la lista de servicios
for servicio in $servicios; do
    manejar_servicio "$servicio"
done
    whiptail --title "Easy setup ASL-Bridge-DMR" --msgbox "Configuracion finalizada" 0 50
    
 ;;
2)
# Lista de servicios a reiniciar
servicios="mmdvm_bridge99.service analog_bridge99.service md380-emu99.service"

# Primero, detener todos los servicios
for servicio in $servicios; do
    if systemctl is-enabled "$servicio" &>/dev/null || systemctl is-active "$servicio" &>/dev/null; then
        echo "Deteniendo $servicio"
        sudo systemctl stop "$servicio"
    fi
done

# Esperar un momento para asegurarse de que todos los servicios se detengan completamente
sleep 5

# Luego, iniciar todos los servicios
for servicio in $servicios; do
    echo "Iniciando $servicio"
    sudo systemctl start "$servicio"
    sudo systemctl enable "$servicio" &>/dev/null
done
 ;;
3)
# Lista de servicios a reiniciar
servicios="mmdvm_bridge99.service analog_bridge99.service md380-emu99.service"

# Recorre la lista de servicios y verifica si están activos
for servicio in $servicios; do
    if systemctl is-enabled "$servicio" &>/dev/null || systemctl is-active "$servicio" &>/dev/null; then
        echo "stop $servicio"
        systemctl disable "$servicio"
        systemctl stop "$servicio"
    fi
done
 ;;
4)
nano /opt/user99/MMDVM_Bridge.ini ;;
5)
# Lista de servicios a reiniciar
servicios="mmdvm_bridge99.service analog_bridge99.service md380-emu99.service"

# Recorre la lista de servicios y verifica si están activos
for servicio in $servicios; do
    if systemctl is-enabled "$servicio" &>/dev/null || systemctl is-active "$servicio" &>/dev/null; then
        echo "stop $servicio"
        systemctl disable "$servicio"
        systemctl stop "$servicio"
    fi
done
rm /opt/user99/ -r > output.log 2>&1
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/*
 ;;
6)
break
    ;;
esac
done
exit 0
EOF
fi
#########
# Verificar si existe algún archivo que comience con "menu-asl" en /bin/
if ls /bin/menu-asl* >/dev/null 2>&1; then
  # Dar permisos de ejecución a los archivos
  chmod +x /bin/menu-asl
  chmod +x /bin/menu-aslb
  chmod +x /bin/menu-asle
  chmod +x /bin/menu-allmon3

  # Crear enlaces simbólicos
  ln -sf /bin/menu-aslb /bin/MENU-ASLB
  ln -sf /bin/menu-asle /bin/MENU-ASLE
  ln -sf /bin/menu-asl /bin/MENU-ASL
  ln -sf /bin/menu-allmon3 /bin/MENU-ALLMON3
fi
chmod +x /bin/MENU*
