#!/bin/bash
SCRIPT_NAME="direwolf.sh"

# Registra el inicio en /opt/curl.txt
echo "Inicio: $SCRIPT_NAME" >> /opt/curl.txt
cd /
if systemctl status direwolf.service |grep active >/dev/null 2>&1
then systemctl stop direwolf.service

fi
if systemctl status gpsd.socket |grep active >/dev/null 2>&1
then systemctl stop gpsd.socket gpsd.service

fi
if [ -d "/opt/direwolf" ]
then
   rm -r /opt/direwolf
 #echo "found file"

fi
if [ -d "/opt/direwolf_webstat" ]
then
   rm -r /opt/direwolf_webstat
 #echo "found file"

fi
if [ -f "/usr/local/bin/direwolf" ]
then
   rm /usr/local/bin/direwolf
 #echo "found file"

fi

#########################################################################################################################
#                                  requeriments
#########################################################################################################################

#!/bin/bash

# Aplicaciones a verificar e instalar
#apps=("git" "gcc" "g++" "make" "cmake" "libasound2-dev" "libudev-dev" "gpsd" "libgps-dev" "gpsd-clients" "gpsd-tools" "chrony")

#########################################################################################################################
#                              audio raspberry
#########################################################################################################################
if [ "$(cat /proc/cpuinfo | grep 'Raspberry')" != "" ]; then
sudo cat > /etc/asound.conf  <<- "EOFA"
pcm.!default {
  type hw
  card 1
}

ctl.!default {
  type hw
  card 1
}
EOFA
fi
#########################################################################################################################
#                                  GPSD
#########################################################################################################################
sudo cat > /etc/udev/rules.d/49-usb-gps.rules  <<- "EOF"
KERNEL=="ttyACM[0-9]*", SUBSYSTEM=="tty", ATTRS{idVendor}=="1546", ATTRS{idProduct}=="01a7", SYMLINK="ttyACM0"
EOF
sudo udevadm control --reload-rules

sudo cat > /etc/default/gpsd  <<- "EOF"
START_DAEMON="true"
GPSD_OPTIONS="-r -n"
DEVICES="/dev/ttyACM0"
USBAUTO="true"

EOF
#
archivo="/etc/chrony/chrony.conf"
palabra=("refclock SHM 0 offset 0.5 delay 0.2 refid NMEA")

for palabra in "${palabra[@]}"
do

if grep -i -E "$palabra" "$archivo" >/dev/null 2>&1; then
   echo "line found"
 else
    echo "$palabra">> "$archivo"
fi
done
systemctl stop gpsd.socket gpsd.service
sudo cat > /lib/systemd/system/gpsd.service  <<- "EOFT"
[Unit]
Description=GPS (Global Positioning System) Daemon
Requires=gpsd.socket
# Needed with chrony SOCK refclock
After=chronyd.service

[Service]
Type=forking
EnvironmentFile=-/etc/default/gpsd
ExecStart=/usr/sbin/gpsd $GPSD_OPTIONS $DEVICES
ExecStartPost=bash -c 'sleep 3 && gpsctl --nmea'

[Install]
WantedBy=multi-user.target
Also=gpsd.socket

EOFT
sed -i "s/ListenStream=127.0.0.1:2947/#ListenStream=127.0.0.1:2947/g" /lib/systemd/system/gpsd.socket
sed -i "s/#ListenStream=0.0.0.0:2947/ListenStream=0.0.0.0:2947/g" /lib/systemd/system/gpsd.socket
systemctl daemon-reload
sudo ln -sf /lib/systemd/system/gpsd.service /etc/systemd/system/multi-user.target.wants/
systemctl enable  chrony
systemctl restart gpsd.socket gpsd.service
systemctl enable gpsd.socket gpsd.service
systemctl is-active gpsd
systemctl is-active chrony
#########################################################################################################################
#                                     direwolf
#########################################################################################################################
cd /opt/
	
git clone https://github.com/wb2osz/direwolf.git &&
cd direwolf
git checkout dev
mkdir build
cd build
cmake .. &&
make -j4 &&
sudo make install
make install-conf

cp /usr/local/bin/direwolf /opt/direwolf/direwolf0
#Direwolf1
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=1iVLnl4KTbWg28xeGJBv_bq5LqweDCPZA' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=1iVLnl4KTbWg28xeGJBv_bq5LqweDCPZA" -O /opt/direwolf/direwolf1 && rm -rf /tmp/cookies.txt &&
#Direwolf2
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=1l3wLd4L0JVdVReqG5E58briA3_4KtUYK' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=1l3wLd4L0JVdVReqG5E58briA3_4KtUYK" -O /opt/direwolf/direwolf2 && rm -rf /tmp/cookies.txt &&

###################

sudo cat > /lib/systemd/system/direwolf.service  <<- "EOF"
[Unit]
Description=Direwolf Service
After=multi-user.target

[Service]
ExecStart=sudo direwolf -t 0 -c /opt/direwolf/dw.conf
Restart=always
RestartSec=5s

[Install]
WantedBy=multi-user.target

EOF
########
sudo cat > /opt/direwolf/rtl.sh  <<- "EOF"
#!/bin/sh
###########################################################
#                                                         #
#       configuration file device RTL-SDR                 #
#                                                         #
#         Linux version setting by hp3icc                 #
#                                                         #
###########################################################


rtl_fm -M fm -f 144.39M -p 0 -s 22050 -g 12 - | /usr/local/bin/direwolf -l /var/log/direwolf -t 0 -c /opt/direwolf/sdr.conf -r 22050 -D 1 -B 1200 - #-l /var/log/direwolf



EOF
#
sudo chmod +x /opt/direwolf/rtl.sh
#
sudo cat > /opt/direwolf/sdr.conf <<- "EOF"
#############################################################
#                                                           #
#       Configuration file for DireWolf                     #
#                                                           #
#         Linux version setting by hp3icc                   #
#                                                           #
#                emq-TE1+                                   #
#                                                           #
#        configuration for SDR RX-only IGate.               #
#############################################################
ADEVICE null null
CHANNEL 0
MYCALL HP3ICC-10
PBEACON sendto=IG delay=0:40 every=30 symbol="/r" lat=08^31.27N long=080^21.59W comment="SDR APRS RX-IGATE / Raspbian Proyect by hp3icc"
# First you need to specify the name of a Tier 2 server.
# The current preferred way is to use one of these regional rotate addresses:
#       noam.aprs2.net          - for North America
#       soam.aprs2.net          - for South America
#       euro.aprs2.net          - for Europe and Africa
#     panama.aprs2.net          - for Central America

IGSERVER panama.aprs2.net:14580

# You also need to specify your login name and passcode.
# Contact the author if you can't figure out how to generate the passcode.
IGLOGIN HP3ICC-10 12345
# That's all you need for a receive only IGate which relays
# messages from the local radio channel to the global servers.
#
#AGWPORT 8000
#KISSPORT 8001
EOF
###
sudo cat > /opt/direwolf/gpsd.conf  <<- "EOF"
#############################################################
#                                                           #
#       Configuration file for DireWolf                     #
#                                                           #
#         Linux version setting by hp3icc                   #
#                                                           #
#                emq-TE1+                                   #
#                                                           #
#        configuration for GPSD TX-only TRACKER.            #
#############################################################
ADEVICE plughw:1,0
ACHANNELS 1
CHANNEL 0

MYCALL HP0XXX-9
MODEM 1200

TXDELAY 75
#PTT CM108
#PTT COM1 RTS
#PTT COM1 RTS -DTR
#PTT /dev/ttyUSB0 RTS
#PTT /dev/ttyUSB0 DTR
#PTT GPIO 25
#PTT GPIO 26

# Enable GPS beaconing

GPSD
TBEACON symbol="/>" comment="Raspberry APRS TRACKER / Raspbian Proyect by hp3icc" VIA=WIDE1-1,WIDE2-1
SMARTBEACONING 25 0:30 5 2:00 0:10 30 255


EOF
#####
sudo cat > /opt/direwolf/dw.conf <<- "EOF"
#############################################################
#                                                           #
#       Configuration file for DireWolf                     #
#                                                           #
#         Linux version setting by hp3icc                   #
#                                                           #
#                emq-TE1ws                                  #
#                                                           #
#############################################################
#############################################################
#                                                           #
#               FIRST AUDIO DEVICE PROPERTIES               #
#               (Channel 0 + 1 if in stereo)                #
#                                                           #
#############################################################
ADEVICE plughw:1,0
#ADEVICE null null
# ADEVICE - plughw:1,0
# ADEVICE UDP:7355 default
# Number of audio channels for this souncard:  1 or 2.
#
ACHANNELS 1
#############################################################
#                                                           #
#               CHANNEL 0 PROPERTIES                        #
#                                                           #
#############################################################
CHANNEL 0
MYCALL HP3ICC-10
MODEM 1200
#MODEM 1200 1200:2200
#MODEM 300  1600:1800
#MODEM 9600 0:0
#
#MODEM 1200 E+ /3
#
#
# If not using a VOX circuit, the transmitter Push to Talk (PTT)
# DON'T connect it directly!
#
# For the PTT command, specify the device and either RTS or DTR.
# RTS or DTR may be preceded by "-" to invert the signal.
# Both can be used for interfaces that want them driven with opposite polarity.
#
# COM1 can be used instead of /dev/ttyS0, COM2 for /dev/ttyS1, and so on.
#
TXDELAY 75
#PTT CM108
#PTT COM1 RTS
#PTT COM1 RTS -DTR
#PTT /dev/ttyUSB0 RTS
#PTT /dev/ttyUSB0 DTR
#PTT GPIO 25
#PTT GPIO 26
# The Data Carrier Detect (DCD) signal can be sent to the same places
# as the PTT signal.  This could be used to light up an LED like a normal TNC.
#DCD COM1 -DTR
#DCD GPIO 24
#pin18 (GPIO 24) - (cathode) LED (anode) - 270ohm resistor - 3.3v
#DCD GPIO 13
#############################################################
#                                                           #
#               VIRTUAL TNC SERVER PROPERTIES               #
#                                                           #
#############################################################
#
# Dire Wolf acts as a virtual TNC and can communicate with
# client applications by different protocols:
#
#       - the "AGW TCPIP Socket Interface" - default port 8000
#       - KISS protocol over TCP socket - default port 8001
#       - KISS TNC via pseudo terminal   (-p command line option)
#
#Setting to 0 disables UI-proto only AGW and TCP-KISS ports
AGWPORT 8000
KISSPORT 8001
#KISSPORT 0
#
# It is sometimes possible to recover frames with a bad FCS.
# This applies to all channels.
#       0  [NONE] - Don't try to repair.
#       1  [SINGLE] - Attempt to fix single bit error.  (default)
#       2  [DOUBLE] - Also attempt to fix two adjacent bits.
#       ... see User Guide for more values and in-depth discussion.
#
#FIX_BITS 0
#Enable fixing of 1 bits and use generic AX25 heuristics data (not APRS heuristi$
#FIX_BITS 1 AX25
#
#############################################################
#                                                           #
#               BEACONING PROPERTIES                        #
#                                                           #
#############################################################
#
#GPSD
#TBEACON delay=0:05 every=20 symbol="/d"  comment="APRS DIGI / Raspbian Proyect by hp3icc" via=WIDE2-2
#PBEACON delay=0:05 every=20 symbol="/r" lat=08^31.27N long=080^21.59W comment="APRS DIGI-IGATE / Raspbian Proyect by hp3icc" via=WIDE2-2
#PBEACON sendto=IG delay=0:60 every=30 symbol="/r" lat=08^31.27N long=080^21.59W comment="APRS DIGI-IGATE / Raspbian Proyect by hp3icc"
#############################################################
#                                                           #
#               DIGIPEATER PROPERTIES                       #
#                                                           #
#############################################################
DIGIPEAT 0 0 ^WIDE[3-7]-[1-7]$|^TEST$ ^WIDE[12]-[12]$ TRACE
FILTER 0 0 t/poimqstunw
#############################################################
#                                                           #
#               INTERNET GATEWAY                            #
#                                                           #
#############################################################
# First you need to specify the name of a Tier 2 server.
# The current preferred way is to use one of these regional rotate addresses:
#       noam.aprs2.net          - for North America
#       soam.aprs2.net          - for South America
#       euro.aprs2.net          - for Europe and Africa
#     panama.aprs2.net          - for Central America

#IGSERVER panama.aprs2.net:14580

#IGLOGIN HP0XXX-00  12345
IGTXVIA 0 WIDE2-2
#WIDE1-1,WIDE2-1
#WIDE2-2
#
#
#IGFILTER b/HP0XXX-00
#IGFILTER p/HP
#m/600
#
FILTER IG 0 t/p
#poimqstunw
IGTXLIMIT 6 10
#
EOF
#########################################################################################################################
#                                     direwolf - dashboard
#########################################################################################################################
cd /opt
git clone https://github.com/IZ7BOJ/direwolf_webstat.git
#cd /opt/direwolf_webstat
sudo sed -i "s/144.800  VHF Port/144.390MHz VHF APRS/g" /opt/direwolf_webstat/config.php 
sudo sed -i "s/0,1/0/g" /opt/direwolf_webstat/config.php 
sudo sed -i 's/href="https:\/\/github.com\/IZ7BOJ\/direwolf_webstat" target/href="https:\/\/gitlab.com\/hp3icc\/emq-TE1\/" target="_blank">emq-TE1+ Raspbian Proyect<\/a> by HP3ICC, <a href="https:\/\/github.com\/IZ7BOJ\/direwolf_webstat" target/' /opt/direwolf_webstat/summary.php
#
#########################################################################################################################
#                                     rtl-sdr
#########################################################################################################################

sudo cat > /etc/modprobe.d/raspi-blacklist.conf <<- "EOF"
blacklist snd_bcm2835
# blacklist spi and i2c by default (many users don't need them)
#blacklist spi-bcm2708
#blacklist i2c-bcm2708
blacklist snd-soc-pcm512x
blacklist snd-soc-wm8804
# dont load default drivers for the RTL dongle
blacklist dvb_usb_rtl28xxu
blacklist rtl_2832
blacklist rtl_2830
EOF
################################

cd /opt
if [[ -d "/opt/rtl-sdr" ]]
then
	rm -r /opt/rtl-sdr
fi
if [[ -f "/etc/udev/rules.d/rtl-sdr.rules" ]]
then
 sudo rm /etc/udev/rules.d/rtl-sdr.rules
fi
if [[ -f "/etc/udev/rules.d/rtl-sdr.rules" ]]
then
 sudo rm /etc/udev/rules.d/rtl-sdr.rules
fi

apps=("cmake" "build-essential" "libusb-1.0-0-dev" "unzip")

# 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..."
        sudo apt-get install -y $app
        echo "$app instalado correctamente."
    else
        echo "$app ya está instalado."
    fi
}

# Verificar e instalar cada aplicación
for app in "${apps[@]}"; do
    check_and_install $app
done

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=14owBT_XWwA4uK5a4I8wepvd4YrC2JErh' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=14owBT_XWwA4uK5a4I8wepvd4YrC2JErh" -O /opt/rtl-sdr-te1ws.zip && rm -rf /tmp/cookies.txt &&
sudo unzip rtl-sdr-te1ws.zip
sudo rm rtl-sdr-te1ws.zip

#git clone git://git.osmocom.org/rtl-sdr.git
cd rtl-sdr
mkdir build
cd build
cmake ../ -DINSTALL_UDEV_RULES=ON
make clean
make
make install
sudo ldconfig
sudo cp /opt/rtl-sdr/rtl-sdr.rules /etc/udev/rules.d

##########
systemctl daemon-reload

sudo systemctl disable gpsd.socket gpsd.service
# Registra el final en /opt/curl.txt
echo "Finalizado: $SCRIPT_NAME" >> /opt/curl.txt
