#!/bin/bash
# Nombre del script
SCRIPT_NAME="data-mmdvm.sh"

# Registra el inicio en /opt/curl.txt
echo "Inicio: $SCRIPT_NAME" >> /opt/curl.txt
(crontab -l | grep -v "sh /opt/data-file.sh") | crontab -
cat > /opt/data-mmdvm.py <<- "EOFXC"
import os
import subprocess
import re

APRSHOSTS = "/opt/data-files/APRSHosts.txt"
DCSHOSTS = "/opt/data-files/DCS_Hosts.txt"
DExtraHOSTS = "/opt/data-files/DExtra_Hosts.txt"
DMRIDFILE = "/opt/data-files/DMRIds.dat"
DMRIDFILE_ALTERNATE = "/opt/data-files/DMRId.dat"
DMRHOSTS = "/opt/data-files/DMR_Hosts.txt"
DPlusHOSTS = "/opt/data-files/DPlus_Hosts.txt"
P25HOSTS = "/opt/data-files/P25Hosts.txt"
M17HOSTS = "/opt/data-files/M17Hosts.txt"
YSFHOSTS = "/opt/data-files/YSFHosts.txt"
FCSHOSTS = "/opt/data-files/FCSHosts.txt"
XLXHOSTS = "/opt/data-files/XLXHosts.txt"
NXDNIDFILE = "/opt/data-files/NXDN.csv"
NXDNHOSTS = "/opt/data-files/NXDNHosts.txt"
TGLISTBM = "/opt/data-files/TGList_BM.txt"
TGLISTDMR = "/opt/data-files/TGList-DMR.txt"
TGLISTP25 = "/opt/data-files/TGList_P25.txt"
TGLISTNXDN = "/opt/data-files/TGList_NXDN.txt"
TGLISTYSF = "/opt/data-files/TGList_YSF.txt"

# How many backups
FILEBACKUP = 1

# Check if the script is running as root
if os.geteuid() != 0:
    print("This script must be run as root")
    exit(1)

# Create backup of old files (only the most recent backup will be kept)
if FILEBACKUP != 0:
    files_to_backup = [
        APRSHOSTS, DCSHOSTS, DExtraHOSTS, DMRIDFILE, DMRHOSTS,
        DPlusHOSTS, P25HOSTS, M17HOSTS, YSFHOSTS, FCSHOSTS,
        XLXHOSTS, NXDNIDFILE, NXDNHOSTS, TGLISTBM, TGLISTDMR,
        TGLISTP25, TGLISTNXDN, TGLISTYSF
    ]

    for file in files_to_backup:
        # Eliminar cualquier backup previo del archivo antes de crear uno nuevo
        existing_backups = [f for f in os.listdir() if f.startswith(f"{file}.")]
        for backup in existing_backups:
            os.remove(backup)
        
        # Crear el nuevo backup con la fecha actual
        backup_filename = f"{file}.{subprocess.check_output(['date', '+%Y%m%d']).decode().strip()}"
        subprocess.run(['cp', file, backup_filename])

# Prune backups (ya no es necesario, ya que solo mantenemos el backup más reciente)
# Este bloque ha sido eliminado, porque ya gestionamos los backups en la sección anterior.

# Generate Host Files
files_to_generate = [
    (APRSHOSTS, "http://www.pistar.uk/downloads/APRS_Hosts.txt"),
    (DCSHOSTS, "http://www.pistar.uk/downloads/DCS_Hosts.txt"),
    (DMRHOSTS, "http://www.pistar.uk/downloads/DMR_Hosts.txt"),
    (DPlusHOSTS, "http://www.pistar.uk/downloads/DPlus_Hosts.txt"),
    (DExtraHOSTS, "http://www.pistar.uk/downloads/DExtra_Hosts.txt"),
    (DMRIDFILE, "http://datafiles.ddns.net:8888/DMRIds.dat"),
    (P25HOSTS, "http://www.pistar.uk/downloads/P25_Hosts.txt"),
    (M17HOSTS, "http://www.pistar.uk/downloads/M17_Hosts.txt"),
    (YSFHOSTS, "http://www.pistar.uk/downloads/YSF_Hosts.txt"),
    (FCSHOSTS, "http://www.pistar.uk/downloads/FCS_Hosts.txt"),
    (XLXHOSTS, "http://www.pistar.uk/downloads/XLXHosts.txt"),
    (NXDNIDFILE, "http://www.pistar.uk/downloads/NXDN.csv"),
    (NXDNHOSTS, "http://www.pistar.uk/downloads/NXDN_Hosts.txt"),
    (TGLISTBM, "http://www.pistar.uk/downloads/TGList_BM.txt"),
    (TGLISTDMR, "http://www.pistar.uk/downloads/TGList_BM.txt"),
    (TGLISTP25, "http://www.pistar.uk/downloads/TGList_P25.txt"),
    (TGLISTNXDN, "http://www.pistar.uk/downloads/TGList_NXDN.txt"),
    (TGLISTYSF, "http://www.pistar.uk/downloads/TGList_YSF.txt")
]

for dest_file, source_url in files_to_generate:
    subprocess.run(['curl', '--fail', '-o', dest_file, '-s', source_url])

# Additional step for DMRId.dat
subprocess.run(['cp', DMRIDFILE, DMRIDFILE_ALTERNATE])  # Correcting the 'cp' command

# Realizando el reemplazo utilizando Python (sin sed)
with open(DMRIDFILE_ALTERNATE, 'r') as file:
    content = file.read()

# Realizar el reemplazo usando una expresión regular
content = re.sub(r'^([^,]+),([^,]+),([^,]+).*', r'\1 \2 \3', content, flags=re.M)

# Escribir el contenido modificado de vuelta al archivo
with open(DMRIDFILE_ALTERNATE, 'w') as file:
    file.write(content)

# Fix up ircDDBGateway Host Files on v4
if os.path.exists("/opt/data-files/ircddbgateway"):
    ircddbgateway_files = [
        ("DCS_Hosts.txt", DCSHOSTS),
        ("DExtra_Hosts.txt", DExtraHOSTS),
        ("DPlus_Hosts.txt", DPlusHOSTS),
        ("CCS_Hosts.txt", "/opt/data-files/CCS_Hosts.txt"),
    ]

    for ircddbgateway_file, symlink_target in ircddbgateway_files:
        ircddbgateway_path = f"/opt/data-files/ircddbgateway/{ircddbgateway_file}"
        if os.path.exists(ircddbgateway_path) and not os.path.islink(ircddbgateway_path):
            os.remove(ircddbgateway_path)
            os.symlink(symlink_target, ircddbgateway_path)

exit(0)

EOFXC
###
if [ ! -d "/opt/data-files" ];
then
   mkdir /opt/data-files
   chmod 777 /opt/data-files
fi
cat > /opt/mmvm.sh <<- "EOFXE"
#!/bin/bash

# Inicializamos una variable para llevar el control del tiempo
last_update=0

while true; do
  # Verificamos si hay algún servicio activo que comience con "mmdvm", "p25" o "P25"
  active_services=$(systemctl list-units --type=service --state=active | grep -E 'mmdvm|nxdn|ysf|dmr|p25|P25')

  if [[ -n "$active_services" ]]; then
    # Si hay servicios activos y ha pasado al menos 12 horas desde la última actualización, ejecutamos el script
    current_time=$(date +%s)
    if [ $((current_time - last_update)) -ge 43200 ]; then
      echo "Actualizando archivos..."
      /usr/bin/python3 /opt/data-mmdvm.py
      # Actualizamos el tiempo de la última actualización
      last_update=$current_time
    fi
  else
    # Si no hay servicios activos, reiniciamos el tiempo de última actualización
    last_update=0
  fi

  sleep 60  # Espera 1 minuto antes de la próxima verificación
done

EOFXE
chmod +x /opt/mmvm.sh
cat > /lib/systemd/system/data-mmdvm.service <<- "EOFXD"
[Unit]
Description=data-mmdvm
After=multi-user.target
After=network.target

[Service]
ExecStart=/bin/bash /opt/mmvm.sh
Restart=on-failure

[Install]
WantedBy=multi-user.target

EOFXD
systemctl daemon-reload
if systemctl is-active data-mmdvm.service; then
    systemctl stop data-mmdvm.service
    systemctl start data-mmdvm.service
  else
   systemctl start data-mmdvm.service
   systemctl enable data-mmdvm.service 
fi
if [ -z "$(ls -A /opt/data-files/ 2>/dev/null)" ]; then
    echo "First update of Hosts and DMRIds, do not panic because of the message: cannot stat"
    python3 /opt/data-mmdvm.py
fi
(crontab -l | grep -v "python3 /opt/data-mmdvm.py") | crontab -
# Registra el final en /opt/curl.txt
echo "Finalizado: $SCRIPT_NAME" >> /opt/curl.txt
