#!/bin/bash
SCRIPT_NAME="p25cross.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
        apt upgrade -y
        apt --fix-broken install -y
    else
        apt-get update
        apt-get upgrade -y
    fi
fi
if [ -d "/opt/p25bridge" ]
then
   rm -r /opt/p25bridge
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
# Lista de servicios a reiniciar
servicios=("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 status "$servicio" | grep "service; enabled;" >/dev/null 2>&1; then
        echo "stop $servicio"
        sudo systemctl disable "$servicio"
        sudo systemctl stop "$servicio"
    fi
done
if [ ! -f "/opt/P25Gateway/P25Gateway" ]
then
   cd /opt
   git clone https://github.com/g4klx/P25Clients.git
   mv /opt/P25Clients/P25Gateway/ /opt/
   cd /opt/P25Gateway
   make
fi
if [ ! -d "/var/log/mmdvm" ]
then
   mkdir /var/log/mmdvm
fi
sudo chmod 777 /var/log/mmdvm
mkdir /opt/p25bridge
cp /opt/Analog_Bridge/* /opt/p25bridge/
cp /opt/MMDVM_Bridge/* /opt/p25bridge/
cp -r /opt/P25Gateway/* /opt/p25bridge/
cp /opt/md380-emu/* /opt/p25bridge/
sudo chmod +x /opt/p25bridge/*
#########################
sudo cat > /opt/p25bridge/Analog_Bridge_DMR.ini <<- "EOF"
[GENERAL]
decoderFallBack = true     
useEmulator = false   
subscriberFile = ./user.csv
exportMetadata = true

[AMBE_AUDIO]
server = 127.0.0.1
fromDMRPort = 31800
toDMRPort = 31803
ambeMode = DMR
minTxTimeMS = 2000
gatewayDmrId = 714000125
repeaterID = 714000126
txTg = 37500
txTs = 2 
colorCode = 1

[USRP]
server = 127.0.0.1
toASLPort = 32801
fromASLPort = 34801
aslAudio = AUDIO_UNITY
agcGain = -20
dmrAudio = AUDIO_UNITY
dmrGain = 0.35

EOF
sudo cat > /opt/p25bridge/Analog_Bridge_P25.ini <<- "EOF"
[GENERAL]
decoderFallBack = true     
useEmulator = false   
subscriberFile = ./user.csv
exportMetadata = true

[AMBE_AUDIO]
server = 127.0.0.1
fromDMRPort = 34800
toDMRPort = 34803
ambeMode = P25
minTxTimeMS = 2000
gatewayDmrId = 714000125
repeaterID = 714000126
txTg = 37500
txTs = 2 
colorCode = 1

[USRP]
server = 127.0.0.1
toASLPort = 34801
fromASLPort = 32801
aslAudio = AUDIO_UNITY
agcGain = -20
dmrAudio = AUDIO_UNITY
dmrGain = 0.35


EOF
sudo cat > /opt/p25bridge/MMDVM_Bridge.ini <<- "EOF"
[General]
Callsign=HP3ICC
Id=0000000
Timeout=220
Duplex=0

[Info]
RXFrequency=0
TXFrequency=0
Power=1
Latitude=41.7333
Longitude=-50.3999
Height=0
Location=P25 < Bridge > DMR
Description=MMDVM_Bridge
URL=https://groups.io/g/DVSwitch

[Log]
# Logging levels, 0=No logging, 1=Debug, 2=Message, 3=Info, 4=Warning, 5=Error, 6=Fatal
DisplayLevel=0
FileLevel=0
FilePath=/var/log/mmdvm
FileRoot=MMDVM_Bridge

[DMR Id Lookup]
File=/opt/data-files/DMRId.dat
Time=24

[NXDN Id Lookup]
File=/opt/data-files/NXDN.csv
Time=24

[Modem]
Port=/dev/null
RSSIMappingFile=/dev/null
Trace=0
Debug=0

[D-Star]
Enable=0
Module=B

[DMR]
Enable=1
ColorCode=1
EmbeddedLCOnly=1
DumpTAData=0

[System Fusion]
Enable=0

[P25]
Enable=1
NAC=293

[NXDN]
Enable=0
RAN=1
Id=12345

[D-Star Network]
Enable=0
GatewayAddress=127.0.0.1
GatewayPort=20010
LocalPort=20011
Debug=0

[DMR Network]
Enable=1
Address=127.0.0.1
Port=62030
Jitter=240
Local=62136
Password=passw0rd
# for DMR+ see https://github.com/DVSwitch/MMDVM_Bridge/blob/master/DOC/DMRplus_startup_options.md
# for XLX the syntax is: Options=XLX:4009
Options=XLX:4001
Slot1=0
Slot2=1
Debug=0

[System Fusion Network]
Enable=0
LocalAddress=0
LocalPort=3280
GatewayAddress=127.0.0.1
GatewayPort=4280
Debug=0

[P25 Network]
Enable=1
GatewayAddress=127.0.0.1
GatewayPort=42820
LocalPort=32810
Debug=0

[NXDN Network]
Enable=0
#LocalAddress=127.0.0.1
Debug=0
LocalPort=14021
GatewayAddress=127.0.0.1
GatewayPort=14020



EOF
sudo cat > /opt/p25bridge/P25Gateway.ini <<- "EOF"
[General]
Callsign=HP3ICC
RptAddress=127.0.0.1
RptPort=32810
LocalPort=42820
Debug=0
Daemon=0

[Id Lookup]
Name=/opt/data-files/DMRId.dat
Time=24

[Voice]
Enabled=0
#Language=en_GB
#Directory=./Audio

[Log]
# Logging levels, 0=No logging
DisplayLevel=0
FileLevel=0
FilePath=/var/log/mmdvm
FileRoot=P25Gateway
FileRotate=1

[Network]
Port=42810
HostsFile1=/opt/P25Hosts2.txt
#/opt/data-files/P25Hosts.txt
#./P25Hosts.txt
ReloadTime=60
ParrotAddress=127.0.0.1
ParrotPort=42811
P252DMRAddress=127.0.0.1
P252DMRPort=42812
# Enter your P25 TG number below:
Static=7144
Startup=7144
RFHangTime=120
NetHangTime=0
Debug=0

[Remote Commands]
Enable=0
Port=6074

EOF
#
sudo cat > /opt/p25bridge/DVSwitch.ini <<- "EOF"
; MMDVM_Bridge export / import configuration file.
;   This file should be placed along side of MMDVM_Bridge or it can be
;   supplied as a path on the MMDVM_BRIDGE environment variable.
 
; Configure the Quantar Repeater Partner
; Note that the TX and RX ports are already reversed for MMDVM_Bridge <--> Quantar_Bridge
[QUANTAR]
;logFilePath = /var/log/Quantar_Bridge.log
;Address = 127.0.0.1             ; Address to send AMBE TLV frames to (export)
;TXPort = 34803                  ; Port to send AMBE TLV frames to (export)
;RXPort = 34800                  ; Port to listen on (import)
;quantarPort = 1994              ; HDLC frames To/From the Quantar repeater
;logLevel = 2                    ; Show messages and above 0=No logging, 1=Debug, 2=Message, 3=Info, 4=Warning, 5=Error, 6=Fatal
;debug = 0                       ; Debug 0 = off, 1 = on (adds lots of additional messages)
 
; Configure the DMR Partner
; Audio format is AMBE 72 bit
[DMR]
Address = 127.0.0.1             ; Address to send AMBE TLV frames to (export)
TXPort = 31800                  ; Port to send AMBE TLV frames to (export)
RXPort = 31803                  ; Port to listen on (import)
Slot = 2                        ; Export slot
 
; Configure the D-Star Partner
; Audio format is AMBE 48 bit (DSAMBE)
[DSTAR]
;Address = 127.0.0.1             ; Address to send AMBE TLV frames to (export)
;TXPort = 32100                  ; Port to send AMBE TLV frames to (export)
;RXPort = 32103                  ; Port to listen on (import)
;FallbackID = 7140001            ; In case we can not find a valid DMR id in the database, export this one
;ExportTG = 9                    ; Which TG to export
;Slot = 2                        ; Export slot
 
; Configure the NXDN Partner
; Audio format is AMBE 72 bit
[NXDN]
;Address = 127.0.0.1             ; Address to send AMBE TLV frames to (export)
;TXPort = 33100                  ; Port to send AMBE TLV frames to (export)
;RXPort = 33103                  ; Port to listen on (import)
;FallbackID = 7140001            ; In case we can not find a valid DMR id in the database, export this one
;NXDNFallbackID  = 12345         ; Use this ID when the input DMR ID is not found in the database
;Translate = 1234=4321           ; Translate NXDN TG < -- > DMR TG (bidirectional)
;Slot = 2                        ; Export slot
 
; Configure the P25 Partner
; Audio format is IMBE 88 bit
[P25]
Address = 127.0.0.1             ; Address to send AMBE TLV frames to (export)
TXPort = 34800                  ; Port to send AMBE TLV frames to (export)
RXPort = 34803                  ; Port to listen on (import)
Slot = 2                        ; Export slot
 
; Configure the Yaesu Fusion Partner
; Audio format is AMBE 72 bit
; Audio format is IMBE 88 bit
[YSF]
;Address = 127.0.0.1             ; Address to send AMBE TLV frames to (export)
;TXPort = 35100                  ; Port to send AMBE TLV frames to (export)
;RXPort = 35103                  ; Port to listen on (import)
;FallbackID = 7140001            ; In case we can not find a valid DMR id in the database, export this one
;ExportTG = 1234                 ; Which TG to export
;Slot = 2                        ; Export slot

EOF
#
cat > /lib/systemd/system/analog_bridge1.service <<- "EOF"
[Unit]
Description=Analog_Bridge Service
# Description=Place this file in /lib/systemd/system
# Description=N4IRS 03/25/2021


[Service]
User=root
Type=simple
Restart=always
RestartSec=3
StandardOutput=null
#RestartPreventExitStatus=252 253 254
WorkingDirectory=/opt/p25bridge
Environment=AnalogBridgeLogDir=/var/log/dvswitch
#ExecStartPre=/bin/sh -c 'until ping -c1 noip.com; do sleep 1; done;'
ExecStart=/opt/p25bridge/Analog_Bridge /opt/p25bridge/Analog_Bridge_DMR.ini
#Analog_Bridge.ini
ExecStartPost= -/usr/local/sbin/update-config.sh

[Install]
WantedBy=multi-user.target

# 254 matching IDs
# 253 ini parse errors
# 252 dv3000 not found, fallback not enabled

EOF
#
cat > /lib/systemd/system/analog_bridge2.service <<- "EOF"
[Unit]
Description=Analog_Bridge Service2
# Description=Place this file in /lib/systemd/system
# Description=N4IRS 03/25/2021


[Service]
User=root
Type=simple
Restart=always
RestartSec=3
StandardOutput=null
#RestartPreventExitStatus=252 253 254
WorkingDirectory=/opt/p25bridge
Environment=AnalogBridgeLogDir=/var/log/dvswitch
#ExecStartPre=/bin/sh -c 'until ping -c1 noip.com; do sleep 1; done;'
ExecStart=/opt/p25bridge/Analog_Bridge /opt/p25bridge/Analog_Bridge_P25.ini
#Analog_Bridge.ini
ExecStartPost= -/usr/local/sbin/update-config.sh

[Install]
WantedBy=multi-user.target

# 254 matching IDs
# 253 ini parse errors
# 252 dv3000 not found, fallback not enabled

EOF
#
cat > /lib/systemd/system/mmdvm_bridgeP25b.service <<- "EOF"
[Unit]
Description=MMDVM_Bridge Service
# Description=Place this file in /lib/systemd/system
# Description=N4IRS 10/16/2020


[Service]
User=root
Type=simple
Restart=always
RestartSec=3
StandardOutput=null
WorkingDirectory=/opt/p25bridge
#ExecStartPre=/bin/sh -c 'until ping -c1 noip.com; do sleep 1; done;'
ExecStart=/opt/p25bridge/MMDVM_Bridge /opt/p25bridge/MMDVM_Bridge.ini


[Install]
WantedBy=multi-user.target


EOF
#
cat > /lib/systemd/system/p25gatewayP25b.service <<- "EOF"
[Unit]
Description=P25 Gateway Service
# Description=Place this file in /lib/systemd/system
# Description=N4IRS 04/20/2018


[Service]
User=root
Type=simple
Restart=always
RestartSec=3
StandardOutput=null
WorkingDirectory=/opt/p25bridge
ExecStartPre=/bin/sh -c 'until ping -c1 noip.com; do sleep 1; done;'
ExecStart=/opt/p25bridge/P25Gateway /opt/p25bridge/P25Gateway.ini


[Install]
WantedBy=multi-user.target

EOF
#
cat > /lib/systemd/system/md380-emuP25b.service <<- "EOF"
[Unit]
Description=MD-380 Emulator p25bridge
# Description=Place this file in /lib/systemd/system
# Description=N4IRS 10/04/2020

[Service]
User=root
Type=simple
Restart=always
RestartSec=3
StandardOutput=null
WorkingDirectory=/opt/p25bridge
#ExecStartPre=/bin/sh -c 'until ping -c1 noip.com; do sleep 1; done;'
ExecStart=/usr/bin/qemu-arm-static /opt/p25bridge/md380-emu -S 2876


[Install]

WantedBy=multi-user.target

EOF
sudo systemctl daemon-reload
# Registra el final en /opt/curl.txt
echo "Finalizado: $SCRIPT_NAME" >> /opt/curl.txt
