#!/bin/bash
# Nombre del script
SCRIPT_NAME="p25.sh"

# Registra el inicio en /opt/curl.txt
echo "Inicio: $SCRIPT_NAME" >> /opt/curl.txt
# Verificar si el usuario tiene permisos de root
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

# Lista de aplicaciones para verificar e instalar
apps="sudo curl git make build-essential python python3 python3-pip chkconfig git-core lm-sensors python3-websockets python3-psutil wget python3-dev python3-venv libffi-dev libssl-dev cargo pkg-config sed default-libmysqlclient-dev libmysqlclient-dev build-essential zip unzip python3-distutils python3-twisted python3-bitarray rrdtool openssl wavemon gcc g++ cmake php"

# 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
#
if [ -d "/opt/DVReflectors" ]
then
   sudo rm -r /opt/DVReflectors
fi
if [ -d "/opt/P25Reflector" ]
then
   sudo rm -r /opt/P25Reflector
fi
if [ -d "/var/log/P25Reflector" ]
then
   sudo rm -rf /var/log/P25Reflector
fi
mkdir /var/log/P25Reflector
sudo chmod 777 /var/log/P25Reflector
cd /opt	
git clone https://github.com/nostar/DVReflectors.git
mv /opt/DVReflectors/P25Reflector /opt/
cd /opt/P25Reflector/
make clean all
make install
sudo groupadd mmdvm
sudo useradd mmdvm -g mmdvm -s /sbin/nologin
sudo chmod +x *
sudo rm -r /opt/DVReflectors
#cp P25Reflector.sh /usr/local/bin/P25Reflector.sh
#sudo chmod +x /usr/local/bin/P25Reflector.sh
#sudo sed -i "s/PROG_ARGS=.*/PROG_ARGS=\"\/opt\/P25Reflector\/P25Reflector.ini\"/g" /usr/local/bin/P25Reflector.sh
sudo sed -i "s/FilePath=.*/FilePath=\/var\/log\/P25Reflector/g" /opt/P25Reflector/P25Reflector.ini
sudo sed -i "s/Name=.*/Name=\/opt\/data-files\/DMRId.dat/g" /opt/P25Reflector/P25Reflector.ini
sudo sed -i "s/Daemon=.*/Daemon=0/g" /opt/P25Reflector/P25Reflector.ini
cp /opt/P25Reflector/P25Reflector.ini /etc/P25Reflector.ini
#/usr/local/bin/P25Reflector.sh stop
sudo cat > /usr/local/bin/clear-p25-logs.sh <<- "EOF"
#!/bin/bash

log_dir="/var/log/P25Reflector/"

# Verifica si la carpeta de registro existe
if [ -d "$log_dir" ]; then
    # Verifica si hay archivos en la carpeta
    if [ -n "$(ls -A $log_dir)" ]; then
        # Borra todos los archivos en la carpeta
        rm -f $log_dir*
        echo "Se han eliminado todos los archivos en $log_dir"
    else
        echo "No se encontraron archivos en $log_dir"
    fi
else
    echo "La carpeta $log_dir no existe"
fi

EOF
sudo chmod +x /usr/local/bin/clear-p25-logs.sh
sudo cat > /lib/systemd/system/P25Reflector.service <<- "EOF"
[Unit]
Description=P25 Reflector Service
# Description=Place this file in /lib/systemd/system
# Description=N4IRS 01/25/2021

#After=netcheck.service
#Requires=netcheck.service

[Service]
Type=simple
Restart=on-failure
RestartPreventExitStatus=SEGV
RestartSec=3
StandardOutput=null
WorkingDirectory=/opt/P25Reflector
ExecStartPre=/usr/local/bin/clear-p25-logs.sh
#/bin/sh -c 'echo "Starting P25Reflector: [`date +%%T.%%3N`]" >> /var/log/netcheck'
ExecStart=/usr/local/bin/P25Reflector /etc/P25Reflector.ini
#ExecReload=/bin/kill -HUP $MAINPID
KillMode=process

[Install]
WantedBy=multi-user.target

EOF

#################################################################################################################################
#                                                   MMDVMHost - Dashboard WebSocket
#################################################################################################################################
#web
if [ -f "/opt/wdp6" ]
then
   echo "found file"
else
sudo cat > /opt/wdp6 <<- "EOFX"
##############################################
# Select number port, P25Reflector Dashboard #
##############################################

Web-Dashboar-Port:  80

EOFX
fi
if [ -d "/opt/P25Reflector-Dashboard" ]
then
   sudo rm -r /opt/P25Reflector-Dashboard
fi
if [ -d "/var/www/p25" ]
then
   sudo rm -r /var/www/p25
fi
cd /opt
#git clone https://gitlab.com/hp3icc/p25reflector-dashboard.git /opt/p25reflector-dashboard
git clone https://github.com/ShaYmez/P25Reflector-Dashboard.git
if [ ! -d "/opt/P25Reflector-Dashboard/config" ]
then
   mkdir /opt/P25Reflector-Dashboard/config
fi
sudo cat > /opt/P25Reflector-Dashboard/config/config.php <<- "EOF"
<?php
# This is an auto-generated config-file!
# Be careful, when manual editing this!

date_default_timezone_set('UTC');
define("P25REFLECTORNAME", "P25 Reflector");
define("P25REFLECTORLOGPATH", "/var/log/P25Reflector");
define("P25REFLECTORLOGPREFIX", "P25Reflector");
define("P25REFLECTORINIPATH", "/etc/");
define("P25REFLECTORINIFILENAME", "P25Reflector.ini");
define("P25REFLECTORPATH", "/usr/local/bin/");
define("TIMEZONE", "America/Panama");
define("LOGO", "/p25.jpg");
define("REFRESHAFTER", "60");
define("TEMPERATUREALERT", "on");
define("TEMPERATUREHIGHLEVEL", "60");
define("SHOWQRZ", "on");
?>

EOF
#!/bin/bash

# Obtener la zona horaria del sistema
timezone=$(timedatectl show --property=Timezone --value)

# Escapar las barras invertidas en la zona horaria
timezone_escaped=$(echo "$timezone" | sed 's/\//\\\//g')

# Actualizar el archivo de configuración con la zona horaria
sudo sed -i "s/define(\"TIMEZONE.*/define(\"TIMEZONE\", \"$timezone_escaped\");/g" /opt/P25Reflector-Dashboard/config/config.php
#
if [ ! -d "/var/www" ]
then
   sudo mkdir /var/www
fi
variable2=$(date +'%Y' | tail -c 5)
sudo sed -i -e "\$i\\</div> <p style=\"text-align: center;\"><span class=\"text-muted\"><a title=\"Raspbian Proyect by HP3ICC © 2018-$variable2\" target=\"_blank\" href=https:\/\/gitlab.com\/hp3icc\/emq-TE1\/>Script project: emq-TE1+<\/a><\/span>" /opt/P25Reflector-Dashboard/index.php
sudo mkdir /var/www/p25
sudo cp -Rf /opt/P25Reflector-Dashboard/* /var/www/p25/
rm /var/www/p25/setup.php
#
sudo chown -R www-data:www-data /var/www
sudo chmod -R 775 /var/www
sudo chown -R www-data:www-data /var/www/p25
sudo chmod -R 775 /var/www/p25
#
systemctl daemon-reload
# Registra el final en /opt/curl.txt
echo "Finalizado: $SCRIPT_NAME" >> /opt/curl.txt
