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

# Registra el inicio en /opt/curl.txt
echo "Inicio: $SCRIPT_NAME" >> /opt/curl.txt
#################################################################################################################################
#                                                      i2c
#################################################################################################################################
cd /boot
if [ -f "/boot/cmdline.txt" ]
then
  sudo sed -i 's/console=serial0,115200 //' /boot/cmdline.txt
fi
if [ -f "/boot/firmware/cmdline.txt" ]
then
  sudo sed -i 's/console=serial0,115200 //' /boot/firmware/cmdline.txt
fi
sudo systemctl stop serial-getty@ttyAMA0.service
sudo systemctl stop bluetooth.service
sudo systemctl disable serial-getty@ttyAMA0.service
sudo systemctl disable bluetooth.service

archivos=("/boot/config.txt" "/boot/firmware/config.txt")
palabra=("enable_uart=1" "dtoverlay=pi3-disable-bt" "dtparam=spi=on")

# Iterar sobre cada archivo
for archivo in "${archivos[@]}"
do
  # Verificar si el archivo existe
  if [ -f "$archivo" ]; then
    # Iterar sobre cada palabra
    for p in "${palabra[@]}"
    do
      # Ignorar líneas de comentarios y verificar si la palabra ya está en el archivo
      if grep -i -E "^[^#]*$p" "$archivo" >/dev/null 2>&1; then
        # Si la palabra ya está, no hacer nada
        continue
      else
        # Si la palabra no está, agregarla al final del archivo
        echo "$p" >> "$archivo" 2>/dev/null
      fi
    done
  fi
done

for archivo in "/boot/config.txt" "/boot/firmware/config.txt"; do
    sudo sed -i 's/#dtparam=i2c_arm=on/dtparam=i2c_arm=on/' "$archivo" 2>/dev/null
    sudo sed -i 's/dtparam=audio=on/#dtparam=audio=on/' "$archivo" 2>/dev/null
    sudo sed -i 's/#dtparam=spi=on/dtparam=spi=on/' "$archivo" 2>/dev/null
    sudo sed -i 's/#dtoverlay=pi3-disable-bt/dtoverlay=pi3-disable-bt/' "$archivo" 2>/dev/null
    sudo sed -i 's/#enable_uart=1/enable_uart=1/' "$archivo" 2>/dev/null
done

sudo cat > /lib/systemd/system/monp.service  <<- "EOF"
[Unit]
Description=sudo modprobe i2c-dev
#Wants=network-online.target
#After=syslog.target network-online.target

[Service]
#User=root
#ExecStartPre=/bin/sleep 1800
ExecStart=sudo modprobe i2c-dev
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

sudo systemctl enable monp.service
#################################################################################################################################
#                                                        MMDVMHost
#################################################################################################################################

#apps=("git" "make" "build-essential" "libusb-1.0-0-dev" "python" "python3" "python3-pip" "chkconfig" "git-core" "libi2c-dev" "i2c-tools" "lm-sensors")

if [ ! -d "/var/log/mmdvmh" ]
then
  mkdir /var/log/mmdvmh
fi
if [ -d "/opt/MMDVMHost" ]
then
  rm -r /opt/MMDVMHost
fi
cd /opt
git clone https://github.com/g4klx/MMDVMHost.git
#git clone https://github.com/hp3icc/MMDVMHost.git
cd /opt/MMDVMHost
sudo make clean

git clone https://github.com/hallard/ArduiPi_OLED
cd ArduiPi_OLED
sudo make
cd /opt/MMDVMHost/
make clean
sudo make -f Makefile.Pi.OLED
sudo make install

groupadd mmdvm 
useradd mmdvm -g mmdvm -s /sbin/nologin 
chown mmdvm /var/log/
#######
sudo cat > /lib/systemd/system/mmdvmh.service  <<- "EOF"
[Unit]
Description=MMDVM Host Service
After=syslog.target network.target

[Service]
#User=root
#Type=simple
#Restart=always
#RestartSec=3
#StandardOutput=null
WorkingDirectory=/opt/MMDVMHost
#ExecStartPre=/bin/sleep 15
ExecStart=/opt/MMDVMHost/MMDVMHost /opt/MMDVMHost/MMDVM.ini
Restart=on-failure

[Install]
WantedBy=multi-user.target

EOF
#
sudo cat > /opt/MMDVMHost/MMDVM.ini  <<- "EOF"
[Service]
ServiceStart=0

[General]
# Coloque su indicativo
Callsign=HP3ICC
# Coloque su DMRID de 7 digitos mas 2 digitos para su conexion
Id=000000000
Timeout=300
Duplex=0
ModeHang=10
#RFModeHang=10
#NetModeHang=3
#Display=None
Display=OLED
#Display=Nextion
Daemon=0

[Info]
# Colocar frecuencia 9 digitos sin puntos
RXFrequency=433400000
TXFrequency=433400000
Power=1
# The following lines are only needed if a direct connection to a DMR master is being used
Latitude=0.0
Longitude=0.0
Height=0
Location=Panama
Description=emq-TE1-MMDVM
URL=https://gitlab.com/hp3icc/emq-TE1

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

[CW Id]
Enable=0
Time=10
# Callsign=

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

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

[Modem]
# Valid values are "null", "uart", "udp", and (on Linux) "i2c"
Protocol=uart
# The port and speed used for a UART connection
# UARTPort=\\.\COM4
# UARTPort=/dev/ttyACM0
UARTPort=/dev/ttyAMA0
UARTSpeed=115200
#460800
# The port and address for an I2C connection
I2CPort=/dev/i2c
I2CAddress=0x22
# IP parameters for UDP connection
ModemAddress=192.168.2.100
ModemPort=3334
LocalAddress=192.168.2.1
LocalPort=3335

TXInvert=1
RXInvert=0
PTTInvert=0
TXDelay=100
RXOffset=0
TXOffset=0
DMRDelay=0
RXLevel=50
TXLevel=50
RXDCOffset=0
TXDCOffset=0
RFLevel=50
# CWIdTXLevel=50
# D-StarTXLevel=50
DMRTXLevel=50
YSFTXLevel=50
# P25TXLevel=50
# NXDNTXLevel=50
# M17TXLevel=50
# POCSAGTXLevel=50
# FMTXLevel=50
# AX25TXLevel=50
RSSIMappingFile=RSSI.dat
UseCOSAsLockout=0
Trace=0
Debug=0

[Transparent Data]
Enable=0
RemoteAddress=127.0.0.1
RemotePort=40094
LocalPort=40095
# SendFrameType=0

[D-Star]
Enable=0
Module=C
SelfOnly=0
AckReply=1
AckTime=750
AckMessage=0
ErrorReply=1
RemoteGateway=0
# ModeHang=10
WhiteList=

[DMR]
Enable=1
Beacons=0
BeaconInterval=60
BeaconDuration=3
ColorCode=1
SelfOnly=0
EmbeddedLCOnly=1
DumpTAData=0
# Prefixes=234,235
# Slot1TGWhiteList=
# Slot2TGWhiteList=
CallHang=3
TXHang=4
# ModeHang=10
# OVCM Values, 0=off, 1=rx_on, 2=tx_on, 3=both_on, 4=force off
# OVCM=0

[System Fusion]
Enable=1
LowDeviation=0
SelfOnly=0
TXHang=4
RemoteGateway=0
# ModeHang=10

[P25]
Enable=0
NAC=293
SelfOnly=0
OverrideUIDCheck=0
RemoteGateway=0
TXHang=5
# ModeHang=10

[NXDN]
Enable=0
RAN=1
SelfOnly=0
RemoteGateway=0
TXHang=5
# ModeHang=10

[M17]
Enable=0
CAN=0
SelfOnly=0
TXHang=5
# ModeHang=10

[POCSAG]
Enable=0
Frequency=439987500

[FM]
Enable=0
# Callsign=G4KLX
CallsignSpeed=20
CallsignFrequency=1000
CallsignTime=10
CallsignHoldoff=0
CallsignHighLevel=50
CallsignLowLevel=20
CallsignAtStart=1
CallsignAtEnd=1
CallsignAtLatch=0
RFAck=K
ExtAck=N
AckSpeed=20
AckFrequency=1750
AckMinTime=4
AckDelay=1000
AckLevel=50
# Timeout=180
TimeoutLevel=80
CTCSSFrequency=88.4
CTCSSThreshold=30
# CTCSSHighThreshold=30
# CTCSSLowThreshold=20
CTCSSLevel=20
KerchunkTime=0
HangTime=7
# AccessMode values are:
#   0 - Carrier access with COS
#   1 - CTCSS only access without COS
#   2 - CTCSS only access with COS
#   3 - CTCSS only access with COS to start, then carrier access with COS
AccessMode=1
# LinkMode=1 to remove almost all of the logic control
LinkMode=0
COSInvert=0
NoiseSquelch=0
SquelchThreshold=30
# SquelchHighThreshold=30
# SquelchLowThreshold=20
RFAudioBoost=1
MaxDevLevel=90
ExtAudioBoost=1
# ModeHang=10

[AX.25]
Enable=0
TXDelay=300
RXTwist=6
SlotTime=30
PPersist=128
Trace=1

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

#########################################################
#       DMR   NETWORK  SETTING                          #
#########################################################
[DMR Network]
Enable=1
#############################################
#  Gateway - Multi DMR Server - DMRGateway  #
#############################################
#Type=Gateway
#LocalAddress=127.0.0.1
#LocalPort=62034
#RemoteAddress=127.0.0.1
#RemotePort=62033
#
#############################################
#  Direct - single server                   #
#############################################
Type=Direct
RemoteAddress=7141.adn.systems
RemotePort=62031
Password=passw0rd
#
#########################################################
Jitter=240
Slot1=1
Slot2=1
# No active linea de Option para TG estaticos, si utiliza BM,TGIF,DMR-Central
# Puede activar linea de option de selfcare FDMR-Mon y colocar su propia contraseña o 
# utilizar linea de options con opciones de tg estaticos
Options=PASS=abc123
#Options=TS2=714,7144;DIAL=0;VOICE=0;LANG=es_ES;SINGLE=0;TIMER=10;
# ModeHang=3
Debug=0

########################################################
#          YSF  NETWORK  SETTING                       #
########################################################
[System Fusion Network]
Enable=1
#######################
#   YSFGateway MODE   #
#######################
#
#LocalAddress=127.0.0.1
#LocalPort=3330
#GatewayAddress=127.0.0.1
#GatewayPort=4330
#
#############################
# YSF SINGLE REFLECTOR MODE #
#############################
#
GatewayAddress=europelink.pa7lim.nl
GatewayPort=42000
#
##########################################################
# ModeHang=3
Debug=0

[P25 Network]
Enable=0
#LocalAddress=127.0.0.1
#LocalPort=32010
GatewayAddress=127.0.0.1
GatewayPort=42020
# ModeHang=3
Debug=0

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

[M17 Network]
Enable=0
#LocalAddress=127.0.0.1
#LocalPort=17011
GatewayAddress=127.0.0.1
GatewayPort=17010
# ModeHang=3
Debug=0

[POCSAG Network]
Enable=0
#LocalAddress=127.0.0.1
#LocalPort=3800
GatewayAddress=127.0.0.1
GatewayPort=4800
# ModeHang=3
Debug=0

[FM Network]
Enable=0
# Protocol=USRP
#LocalAddress=127.0.0.1
#LocalPort=3810
GatewayAddress=127.0.0.1
GatewayPort=4810
PreEmphasis=1
DeEmphasis=1
TXAudioGain=1.0
RXAudioGain=1.0
# ModeHang=3
Debug=0

[AX.25 Network]
Enable=0
Port=/dev/ttyp7
Speed=9600
Debug=0

[TFT Serial]
# Port=modem
Port=/dev/ttyAMA0
Brightness=50

[HD44780]
Rows=2
Columns=16

# For basic HD44780 displays (4-bit connection)
# rs, strb, d0, d1, d2, d3
Pins=11,10,0,1,2,3

# Device address for I2C
I2CAddress=0x20

# PWM backlight
PWM=0
PWMPin=21
PWMBright=100
PWMDim=16

DisplayClock=1
UTC=0

[Nextion]
Port=modem
#Port=/dev/ttyAMA0
Brightness=50
DisplayClock=1
UTC=0
#Screen Layout: 0=G4KLX 2=ON7LDS
ScreenLayout=2
IdleBrightness=20

[OLED]
Type=3
Brightness=1
Invert=0
Scroll=0
Rotate=0
Cast=0
LogoScreensaver=1

[LCDproc]
Address=localhost
Port=13666
#LocalPort=13667
DimOnIdle=0
DisplayClock=1
UTC=0

[Lock File]
Enable=0
File=/tmp/MMDVM_Active.lck

[Remote Control]
Enable=0
Address=127.0.0.1
Port=7642


EOF
#
#################################################################################################################################
#                                                   MMDVMHost - Dashboard WebSocket
#################################################################################################################################
#apps=("python3-pip" "python3-websockets" "python3-gpiozero" "python3-psutil" "python3-serial")
sudo adduser --system --no-create-home --group mmdvm

if [ -d "/opt/MMDVMHost-Websocketboard" ]
then
   rm -r /opt/MMDVMHost-Websocketboard
 #echo "found file"

fi
cd /opt/
git clone --recurse-submodules -j8 https://github.com/dg9vh/MMDVMHost-Websocketboard
sudo chown -R mmdvm:mmdvm /opt/MMDVMHost-Websocketboard
#
sudo sed '264 a <!--' -i /opt/MMDVMHost-Websocketboard/html/index.html 
sudo sed '266 a -->' -i /opt/MMDVMHost-Websocketboard/html/index.html 
sudo sed -i "s/\`Custom-Headline-Text\`/\`Websocket-Based\`/g"  /opt/MMDVMHost-Websocketboard/html/js/config.js
sudo sed -i "s/about = 1/about = 0/g" /opt/MMDVMHost-Websocketboard/html/js/config.js
sudo sed -i "s/currtx = 1/currtx = 0/g" /opt/MMDVMHost-Websocketboard/html/js/config.js
sudo sed -i "s/qso = 1/qso = 0/g" /opt/MMDVMHost-Websocketboard/html/js/config.js
sudo sed -i "s/dapnet = 1/dapnet = 0/g" /opt/MMDVMHost-Websocketboard/html/js/config.js
sudo sed -i "s/DGIdGateway/YSFGateway/g" /opt/MMDVMHost-Websocketboard/logtailer.ini
sudo sed -i "s/BinaryName5/#BinaryName5/g" /opt/MMDVMHost-Websocketboard/logtailer.ini
sudo sed -i 's/Logdir=\/mnt\/ramdisk/Logdir=\/var\/log\/mmdvmh/' /opt/MMDVMHost-Websocketboard/logtailer.ini
sudo sed -i 's/5678/5679/' /opt/MMDVMHost-Websocketboard/logtailer.ini
sudo sed -i 's/Filerotate=True/Filerotate=False/' /opt/MMDVMHost-Websocketboard/logtailer.ini
sudo sed -i 's/etc\/MMDVM/opt\/MMDVMHost/' /opt/MMDVMHost-Websocketboard/logtailer.ini
sudo sed -i 's/usr\/local\/bin/opt\/MMDVMHost/' /opt/MMDVMHost-Websocketboard/logtailer.ini
sudo sed -i 's/Prefix=MMDVM/Prefix=MMDVMH/' /opt/MMDVMHost-Websocketboard/logtailer.ini
variable2=$(date +'%Y' | tail -c 5)
sudo sed -i "s/switch theme.*/switch theme<\/a><\/span>  <\/div> <p style=\"text-align: center;\"><span class=\"text-muted\"><a title=\"Script Proyect by HP3ICC © 2018-$variable2\" target=\"_blank\" href=https:\/\/gitlab.com\/hp3icc\/emq-TE1\/>Script project: emq-TE1+<\/a><\/span>/g" /opt/MMDVMHost-Websocketboard/html/index.html
#
cd /opt/MMDVMHost-Websocketboard/html/
sudo sed -i 's/5678/5679/' /opt/MMDVMHost-Websocketboard/html/index.html
sudo sed -i 's/<span class="navbar-brand float:center"><script type="text\/javascript">document.write(customHeadlineText);<\/script><\/span>/<span style="color: #808080;" class="navbar-brand float:center"><script type="text\/javascript">document.write(customHeadlineText);<\/script><\/span>/g'  /opt/MMDVMHost-Websocketboard/html/index.html
sudo sed -i 's/<script type="text\/javascript">document.write(customText);<\/script>/<span style="color: #3cff33;"><script type="text\/javascript">document.write(customText);<\/script>/g'  /opt/MMDVMHost-Websocketboard/html/index.html
sudo sed -i 's/This is an example/MMDVMHost Dashboard/' /opt/MMDVMHost-Websocketboard/html/js/config.js
sudo sed -i 's/you can use all html-tags and multiline-text./MMDVMHost-Websocketboard by DG9VH/' /opt/MMDVMHost-Websocketboard/html/js/config.js
sudo sed -i 's/<span class="navbar-brand float:right">Websocket-Based<\/span>/<span style="color: #808080;" <li>Temperature: <span id="cputemp"><\/span> °C<\/li>/g'  /opt/MMDVMHost-Websocketboard/html/index.html
sudo sed -i 's/<a class="navbar-brand" href="#">MMDVM-Dashboard by DG9VH<\/a>/<h6 style="text-align: center;"><span style="color: #808080;"><a style="color: #808080;" href="https:\/\/github.com\/hp3icc\/emq-TE1ws\/" target="_blank">emq-te1ws Script Proyect by hp3icc<\/a> copyright 2018-YK00<\/span><\/h6>/g'  /opt/MMDVMHost-Websocketboard/html/index.html
variable2=$(date +'%Y' | tail -c 5)
sudo sed -i "s/YK00/$variable2/g"  /opt/MMDVMHost-Websocketboard/html/index.html
#############################
sudo cat > /lib/systemd/system/logtailer-mmdvmh.service <<- "EOF"
[Unit]
Description=Python3 logtailer for MMDVMDash
After=network.target

[Service]
#Type=simple
#User=mmdvm
#Group=mmdvm
#Restart=always
#ExecStartPre=/bin/sleep 5
# Modify for different location of Python3 or other port
WorkingDirectory=/opt/MMDVMHost-Websocketboard/
ExecStart=/usr/bin/python3 /opt/MMDVMHost-Websocketboard/logtailer.py
Restart=on-failure

[Install]
WantedBy=multi-user.target


EOF
#################
# MMDVMCAL
if [ -d "/opt/MMDVMCal" ]
then
  rm -r /opt/MMDVMCal
fi
cd /opt
git clone https://github.com/g4klx/MMDVMCal.git
cd /opt/MMDVMCal/
sudo make clean
sudo make
sudo make install
#####################################################################################################################
systemctl daemon-reload
# Registra el final en /opt/curl.txt
echo "Finalizado: $SCRIPT_NAME" >> /opt/curl.txt
