#!/bin/bash
#
# Installs some core Ham Apps 
#   flsuite (flrig, fldigi, flmsgi, flAmp)
#   WSJT-X
#   GridTracker
#   Js8Call
#   HamClock
#   Pat (packet & ARDOP)
# And some utilities for remote access
#   X11VNC
#   NoMachine
#   Tailscale
#
# v1.1: 3-22-23
#   Adds rigctl set mode (USB for ARDOP, FM for packet)
#   Adds flAmp to flSuite
#   Adds instructions for Tailscale
#
# v1.2:  4-9-23
#   Add hamRS 1.0.6 64-bit
#
# v1.3:  4-23-23
#   Add direwolf & YAAC
#
# v1.4:  5-22-23
#   Update Pat (uses AGWPE)
#
# Let us know what other apps you'd like to see!
#


install_OHB () {
echo "

*********************************************
**                                         **
**  INSTALLING OHB                         **
**                                         **
*********************************************

"	
NEW_HOST="44.32.64.64 clearskyinstitute.com"
HOSTS="/etc/hosts"
install_ORIG-BE
echo "$NEW_HOST" | sudo tee -a "$HOSTS"
echo "

*********************************************
**                                         **
**  SUCCESSFULLY INSTALLED OHB             **
**                                         **
*********************************************

"
}


install_HK-COM () {
echo "

*********************************************
**                                         **
**  INSTALLING HAMCLOCK.COM                **
**                                         **
*********************************************

"
NEW_HOST="3.128.20.228 clearskyinstitute.com"
HOSTS="/etc/hosts"
install_ORIG-BE
echo "$NEW_HOST" | sudo tee -a "$HOSTS"
echo "

*********************************************
**                                         **
**  SUCCESSFULLY INSTALLED HAMCLOCK.COM    **
**                                         **
*********************************************

"
}


install_ORIG-BE () {
echo "

*********************************************
**                                         **
**  RESTORING ORIGINAL HAMCLOCK BACK END   **
**                                         **
*********************************************

"
CLEAR_SKY="clearskyinstitute.com"
HOSTS="/etc/hosts"
sudo sed -i "/$CLEAR_SKY/d" "$HOSTS"
rm ~/.hamclock/*.bmp #clear cached images
echo "

*********************************************
**                                         **
**  RESTORED ORIGINAL HAMCLOCK BACKEND     **
**                                         **
*********************************************

"
}


install_nomachine () {
echo "

*********************************************
**                                         **
**  INSTALLING NOMACHINE                   **
**                                         **
*********************************************

"
wget https://inovato.net/ham/files/nomachine_8.4.2_1_arm64.deb
sudo dpkg -i nomachine_8.4.2_1_arm64.deb
rm nomachine_8.4.2_1_arm64.deb
echo "

*********************************************
**                                         **
**  SUCCESSFULLY INSTALLED NOMACHINE       **
**                                         **
*********************************************

"	
}

install_x11vnc () { 
echo "

*********************************************
**                                         **
**  INSTALLING X11VNC                      **
**                                         **
*********************************************

"	# install X11VNC
sudo apt install -y x11vnc
sudo rm /etc/systemd/system/x11vnc.service
cat <<EOT >> x11vnc.service
[Unit]
Description=x11vnc remote desktop server
Wants=network-online.target
After=network-online.target

[Service]
ExecStart=/usr/bin/x11vnc -ncache 10 -geometry 1920x1080 -many -nevershared -display :0 -no6 -auth /var/run/lightdm/root/:0

Restart=on.failure

[Install]
WantedBy=graphical.target
EOT
sudo mv x11vnc.service /etc/systemd/system
sudo systemctl daemon-reload
sudo systemctl start x11vnc
sudo systemctl enable x11vnc.service
echo "

*********************************************
**                                         **
**  SUCCESSFULLY INSTALLED X11VNC          **
**                                         **
*********************************************

"	
}


install_tailscale () {
echo "

*********************************************
**                                         **
**  INSTALLING TAILSCALE                   **
**                                         **
*********************************************

"	
curl -fsSL https://pkgs.tailscale.com/stable/debian/bullseye.noarmor.gpg | sudo tee /usr/share/keyrings/tailscale-archive-keyring.gpg >/dev/null
curl -fsSL https://pkgs.tailscale.com/stable/debian/bullseye.tailscale-keyring.list | sudo tee /etc/apt/sources.list.d/tailscale.list
sudo apt-get update
sudo apt-get install -y tailscale
echo "

*********************************************
**                                         **
**  SUCCESSFULLY INSTALLED TAILSCALE       **
**                                         **
*********************************************

"	
}


install_wsjtx () {
echo "

*********************************************
**                                         **
**  INSTALLING WSJTX/JS8CALL               **
**                                         **
*********************************************

"	
#sudo apt install -y wsjtx js8call
wget https://sourceforge.net/projects/wsjt/files/wsjtx-2.7.0/wsjtx-2.7.0_arm64.deb
sudo dpkg --force-overwrite -i ./wsjtx-2.7.0_arm64.deb
rm ./wsjtx-2.7.0_arm64.deb
# remove these so icons can show (artifact of older build)
if [ -f ~/.local/share/applications/wsjtx.desktop ]; then
	rm ~/.local/share/applications/wsjtx.desktop
fi
if [ -f ~/.local/share/applications/js8call.desktop ]; then
	rm ~/.local/share/applications/js8call.desktop
fi
echo "

*********************************************
**                                         **
**  WSJTX / JS8CALL SUCCESSFULLY INSTALLED **
**                                         **
*********************************************

"
}


install_gridtracker2 () {
echo "

*********************************************
**                                         **
**  INSTALLING GRIDTRACKER                 **
**                                         **
*********************************************

"	
wget https://download2.gridtracker.org/GridTracker2-2.250713.2-arm64.deb
sudo apt -y install ./GridTracker2-2.250713.2-arm64.deb
rm GridTracker2-2.250713.2-arm64.deb
echo "

*********************************************
**                                         **
**  GRIDTRACKER SUCCESSFULLY INSTALLED     **
**                                         **
*********************************************

"	
}

install_hotspot () {
echo "

*********************************************
**                                         **
**  INSTALLING HOTSPOT                     **
**                                         **
*********************************************

"
wget -N https://inovato.net/ham/files/hotspot.tar.gz
tar -xf hotspot.tar.gz
rm hotspot.tar.gz
source hotspot-install
rm hotspot-install
echo "

*********************************************
**                                         **
**  HOTSPOT SUCCESSFULLY INSTALLED         **
**                                         **
*********************************************

"	
}
install_flsuite () {
echo "

*********************************************
**                                         **
**  INSTALLING FLSUITE                     **
**                                         **
*********************************************

"
sudo apt install -y flrig fldigi flmsg flamp
wget https://inovato.net/ham/files/flsuite.tar.gz
tar -xf flsuite.tar.gz
rm flsuite.tar.gz
sudo mv fl* /usr/local/bin
echo "

*********************************************
**                                         **
**  FLSUITE SUCCESSFULLY INSTALLED         **
**                                         **
*********************************************

"	
}

install_pat () {
echo "

*********************************************
**                                         **
**  INSTALLING PAT (Winlink Client)        **
**                                         **
*********************************************

"	
# we need Direwolf (will also install flrig)
install_direwolf

wget https://inovato.net/ham/files/pat.tar.gz
tar -xf pat.tar.gz
rm pat.tar.gz
mkdir -p ~/.config/pat
mv config.json.template ~/.config/pat/config.json.template
cp ~/.config/pat/config.json.template ~/.config/pat/config.json
sudo mv pat /usr/bin/pat
sudo mv pat_config.sh /usr/local/bin
#sudo mv pat_ardop.sh /usr/local/bin
sudo mv pat_packet.sh /usr/local/bin
sudo mv pat.png /usr/share/pixmaps

# Add Pat desktop items
cat >pat-config.desktop << EOF
[Desktop Entry]
Name=Pat Winlink Configure
Icon=pat
Comment=Configure Pat files
Exec=pat_config.sh
Terminal=false
Type=Application
Categories=HamRadio

EOF

cat >pat-packet.desktop << EOF
[Desktop Entry]
Name=Pat Winlink (packet)
Icon=pat
Comment=Pat Winlink using AX.25 (pat-gensio)
Exec=pat_packet.sh
Terminal=true
Type=Application
Categories=HamRadio

EOF

sudo mv pat-config.desktop /usr/local/share/applications/
sudo mv pat-packet.desktop /usr/local/share/applications/

# configure PAT (dialog)
source pat_config.sh
echo "

*********************************************
**                                         **
**  PAT SUCCESSFULLY INSTALLED             **
**                                         **
*********************************************

"
}


install_ardop () {
echo "

*********************************************
**                                         **
**  INSTALLING ARDOP MODEM                 **
**                                         **
*********************************************

"
	
wget https://inovato.net/ham/files/ardopc.tar.gz
tar -xf ardopc.tar.gz
rm ardopc.tar.gz
if [ ! -f ~/.asoundrc.save ]; then
	if [ -f ~/.asoundrc ]; then
		mv ~/.asoundrc ~/.asoundrc.save
	fi
fi
# get sound card info and write to config.json
line=$(aplay -l | grep USB)
card=$(echo "$line" | awk '{print $2}' | tr -d ':')
device=$(echo "$line" | awk '{print $8}' | tr -d ':')
sed -i "s/hw:1,0/hw:$card,$device/g" ./asoundrc

mv ./asoundrc ~/.asoundrc
sudo mv ardopc /usr/local/bin
sudo mv pat_ardop.sh /usr/local/bin
cat >pat-ardop.desktop << EOF
[Desktop Entry]
Name=Pat Winlink (ARDOP)
Icon=pat
Comment=Pat Winlink using ARDOP modem
Exec=pat_ardop.sh
Terminal=true
Type=Application
Categories=HamRadio

EOF
sudo mv pat-ardop.desktop /usr/local/share/applications/
echo "

*********************************************
**                                         **
**  ARDOP SUCCESSFULLY INSTALLED           **
**                                         **
*********************************************

"	 
}


install_hamclock () {
echo "

*********************************************
**                                         **
**  RE-INSTALLING HAMCLOCK                 **
**                                         **
*********************************************

"	
sudo rm ESPHamClock.zip
sudo rm -r ESPHamClock
sudo apt install -y xorg-dev libx11-dev
curl -O https://www.clearskyinstitute.com/ham/HamClock/ESPHamClock.zip 
unzip ESPHamClock.zip 
cd ESPHamClock 
make -j 4 hamclock-3200x1920 
sudo make install
sudo mv /usr/local/bin/hamclock /usr/local/bin/hamclock-4k
sudo make clean
make -j 4 hamclock-1600x960
sudo make install
cd ..
rm ESPHamClock.zip
sudo rm -r ESPHamClock
echo "

*********************************************
**                                         **
**  HAMCLOCK SUCCESSFULLY REINSTALLED      **
**                                         **
*********************************************

"	
}


install_hamrs () {
echo "

*********************************************
**                                         **
**  INSTALLING HAMRS                       **
**                                         **
*********************************************

"
wget https://hamrs-releases.s3.us-east-2.amazonaws.com/1.0.6/hamrs-1.0.6-linux-arm64.AppImage

sudo chmod +x hamrs-1.0.6-linux-arm64.AppImage
sudo mv hamrs-1.0.6-linux-arm64.AppImage /usr/local/bin

cat > hamrs.desktop <<EOF
[Desktop Entry]
Name=HAMRS
Comment=POTA Logging Software
Exec=/usr/local/bin/hamrs-1.0.6-linux-arm64.AppImage
Icon=/usr/share/pixmaps/hamrs-logo.png
Terminal=false
Type=Application
Categories=HamRadio
EOF

sudo mv hamrs.desktop /usr/share/applications/
wget https://inovato.net/ham/files/hamrs-logo.png
sudo mv hamrs-logo.png /usr/share/pixmaps/hamrs-logo.png

echo "

*********************************************
**                                         **
**  HAMRS SUCCESSFULLY INSTALLED           **
**                                         **
*********************************************

"	
}


install_direwolf () {

echo "

*********************************************
**                                         **
**  INSTALLING DIREWOLF                    **
**                                         **
*********************************************

"	
INFO=$(yad --form --width=420 --text-align=center --center --title="direwolf Setup" \
	--separator="|" --item-separator="|" \
	--text="<b>Make sure your rig is connected to the Quadra and powered on before continuing\r\rPlease enter your callsign below:</b>" \
	--field="Callsign" \
	--button="Continue":0 \
        --button="Exit":1 "" "" "")
BUT=$(echo $?)
	
if [ ${BUT} = 1 ]; then
  	exit
fi
callsign=$(echo ${INFO} | awk -F "|" '{print $1}')
callsign=${callsign^^}

# we need at least flRig
if [ ! -f /usr/local/bin/flrig ]; then
	wget https://inovato.net/ham/files/flsuite.tar.gz
	tar -xf flsuite.tar.gz
	rm flsuite.tar.gz
	sudo apt install -y flrig
	sudo mv flrig /usr/local/bin
	rm fldigi flmsg flamp
fi

sudo apt-get install -y libasound2-dev libudev-dev direwolf
rm ~/direwolf.conf
wget https://www.inovato.net/ham/files/direwolf.conf ~/

# use our start_direwolf command to start rigctld/flRig
wget https://inovato.net/ham/files/start_direwolf
sudo chmod +x start_direwolf
sudo mv start_direwolf /usr/local/bin
sudo sed -i 's/\/usr\/bin\/x-terminal-emulator -e direwolf/start_direwolf/' /usr/share/applications/direwolf.desktop

# edit direwolf config to use your callsign, USB soundcard & rigctld/flRig
sed -i "s/N0CALL/${callsign}/" ~/direwolf.conf
# get sound card info and write to direwolf.conf
line=$(aplay -l | grep USB)
card=$(echo "$line" | awk '{print $2}' | tr -d ':')
device=$(echo "$line" | awk '{print $8}' | tr -d ':')

sed -i "s/# ADEVICE  plughw:1,0/ADEVICE  plughw:$card,$device/" ~/direwolf.conf
sed -i '/#PTT\ \/dev\/ttyUSB0\ RTS/a #Change line below if not using Hamlib/flrig for PTT\nPTT RIG 2 localhost:4532' ~/direwolf.conf

# start flrig now so user can configure radio
pid=$(pidof -x flrig)
if [ -z $pid ]; then
    echo "starting flrig"
    flrig &
fi

yad --width=400 --height=100 --title="Direwolf Setup" --wrap \
	--text="\rConfigure your rig in flrig under 'config'/'Setup'/'Transceiver' then close it to save the configuration.\r\rIf you need help, Google your rig model number plus 'flrig'.\r" \
	--button="Exit":1

echo "

*********************************************
**                                         **
**  DIREWOLF SUCCESSFULLY INSTALLED        **
**                                         **
*********************************************

"	
}

install_yaac () {
echo "

*********************************************
**                                         **
**  INSTALLING YAAC                        **
**                                         **
*********************************************

"	

# Script thanks to KM4ACK 73Linux, with minor edits
cd ~
wget --tries 2 --connect-timeout=60 https://www.ka2ddo.org/ka2ddo/YAAC.zip
sudo apt-get install -y librxtx-java default-jre
mkdir -p ${HOME}/YAAC
cd ${HOME}/YAAC || return
	#Fix issue 375 to prevent YAAC from reopening
	if [ -f ${HOME}/YAAC/YAAC ]; then
	rm ${HOME}/YAAC/YAAC
	fi
touch YAAC
echo "#!/bin/bash" >>YAAC
echo "java -jar ${HOME}/YAAC/YAAC.jar" >>YAAC
chmod +x YAAC
cat >yaac.desktop <<EOF
[Desktop Entry]
Name=YAAC
GenericName=YAAC
Comment=APRS Client
Exec=${HOME}/YAAC/YAAC
Icon=~/usr/share/pixmaps/YAAC.png
Terminal=false
Type=Application
Categories=Network;HamRadio;
EOF

sudo mv yaac.desktop /usr/share/applications/
mv ~/YAAC.zip $HOME/YAAC
unzip -o ${HOME}/YAAC/YAAC.zip
rm $HOME/YAAC/YAAC.zip
echo "

*********************************************
**                                         **
**  YAAC SUCCESSFULLY INSTALLED            **
**                                         **
*********************************************

"	
}

install_conky () {

echo "

*********************************************
**                                         **
**  INSTALLING CONKY                       **
**                                         **
*********************************************

"	
# set user info in pat config file
INFO=$(yad --form --width=420 --text-align=center --center --title="Conky Setup" \
	--separator="|" --item-separator="|" \
	--text="<b>Please enter your information below:</b>" \
	--field="Callsign" \
	--field="Six Character Gridsquare" \
	--button="Continue":0 \
        --button="Exit":1 "" "" "")
BUT=$(echo $?)
if [ ${BUT} = 1 ]; then
  	exit
fi
callsign=$(echo ${INFO} | awk -F "|" '{print $1}')
callsign=${callsign^^}
gridsquare=$(echo ${INFO} | awk -F "|" '{print $2}')
gridsquare=${gridsquare^^}

# install conky & GPS support via apt
# remove gpsd first so re-install works
sudo apt remove gpsd
sudo apt install -y conky gpsd gpsd-clients pip
pip install gridtools
wget https://www.inovato.net/ham/files/gpsd
# default is ttyACM0, but if ttyACM1 exists, use it (eg, IC705)
if [ -e /dev/ttyACM1 ]; then
       sed -i "s/ACM0/ACM1/" gpsd
fi       
sudo mv gpsd /etc/default
sudo systemctl enable gpsd
sudo systemctl start gpsd
wget https://www.inovato.net/ham/files/get_gps
#sed -i "s/MYGRID/$gridsquare/" get_gps
sudo chmod +x get_gps
sudo mv get_gps /usr/local/bin
wget https://www.inovato.net/ham/files/get_freq
sudo chmod +x get_freq
sudo mv get_freq /usr/local/bin


# install conkyrc file & related
wget https://www.inovato.net/ham/files/vcgencmd
chmod +x vcgencmd
sudo mv vcgencmd /usr/bin
wget https://www.inovato.net/ham/files/conkyrc
sed -i "s/MYGRID/$gridsquare/" ./conkyrc
sed -i "s/MYCALL/$callsign/" ./conkyrc
mv conkyrc .conkyrc

# menu
cat <<EOF >${HOME}/.local/share/applications/conky.desktop
[Desktop Entry]
Name=Conky
Comment=Conky
GenericName=Conky Screen Background Monitor
Exec=conky --pause=5
Icon=/usr/share/pixmaps/conky-logo.png
Type=Application
Encoding=UTF-8
Terminal=false
Categories=HamRadio
Keywords=Radio
EOF


# misc dependencies
sudo touch ${HOME}/.local/share/WSJT-X/wsjtx.log  #conky will fail to load if this file doesn't exist
sudo touch /var/lib/misc/dnsmasq.leases #conky will fail to load if this file doesn't exist
wget https://inovato.net/ham/files/conky-logo.png
sudo mv conky-logo.png /usr/share/pixmaps/conky-logo.png

# autostart
ln -sf ${HOME}/.local/share/applications/conky.desktop ${HOME}/.config/autostart/conky.desktop

echo "

*********************************************
**                                         **
**  CONKY SUCCESSFULLY INSTALLED           **
**                                         **
*********************************************

"	
}

install_chirp () {

echo "

*********************************************
**                                         **
**  INSTALLING CHIRP                       **
**                                         **
*********************************************

"	

sudo apt -y install python3-wxgtk4.0 pipx
wget https://archive.chirpmyradio.com/chirp_next/next-20240827/chirp-20240827-py3-none-any.whl
pipx install --system-site-packages ./chirp-20240827-py3-none-any.whl
rm ./chirp-20240827-py3-none-any.whl

echo "

****************************************************
**                                                **
**           CHIRP WILL NOW RUN                   **
**  BE SURE TO SAY 'YES' TO CREATE DESKTOP ICON!  **
**                                                **
****************************************************

"

sleep 5
~/.local/bin/chirp

echo "

*********************************************
**                                         **
**  CHIRP SUCCESSFULLY INSTALLED           **
**                                         **
*********************************************

"	
}


#
# Application starts here
#
# make sure yad installed
sudo apt install yad
sudo mkdir /usr/local/share/applications

# display menu
wget -N https://inovato.net/ham/files/install.txt
options_file=install.txt
yad_options=()

while IFS='|' read -r option desc version
do
	yad_options+=(FALSE "$option" "$desc" "$version")
done < $options_file

selected_options=$(yad --height=460 --width=730 --title="Quadra Installer" --center --list --print-all --search-column=2 \
       	--multiple --borders=20 --checklist --grid-lines=hor --column="Select" --column="Name" --column="Description" --column="Version" \
        --text="Select apps to install with SPACE.  You can sort, or search by typing." --button="cancel":1 --button="Install":2 "${yad_options[@]}")
exval=$?
if [ $exval = 1 ]; then
	# cancel button pressed
       exit
fi       

echo "

*********************************************
**                                         **
**  CHECKING DEPENDENCIES                  **
**                                         **
*********************************************

"
sudo apt update

# Make sure we have a HamRadio menu
if [ -f ~/.config/menus/xfce-applications.menu ]; then
	rm ~/.config/menus/xfce-applications.menu
fi

# install our installer in it
if [ ! -f /usr/local/bin/ham_installer ]; then
cat >ham_installer.desktop <<EOF
[Desktop Entry]
Name=Quadra Ham Apps Installer
GenericName=Ham Installer
Comment=Ham Installer
Exec=/usr/local/bin/ham_installer
Icon=/usr/share/icons/gnome/32x32/apps/system-software-install.png
Terminal=true
Type=Application
Categories=HamRadio;
EOF

sudo mv ham_installer.desktop /usr/share/applications
cat >ham_installer <<EOF
#!/bin/bash
cd ~/
wget -N https://inovato.net/ham/install
sudo chmod +x install
./install
EOF

sudo mv ham_installer /usr/local/bin
sudo chmod +x /usr/local/bin/ham_installer
fi 

#sudo apt update
sudo apt install -y extra-xdg-menus
# use updated rig icon instead of CQ icon which is hard to see
wget https://inovato.net/ham/files/hamradio.png
sudo mv hamradio.png /usr/share/pixmaps/CQ.png

# Remove old hand-built Hamradio menu if it exists
if [ -f ~/.config/menus/applications-merged/user-menulibre-ham-radio.menu ]; then
	rm ~/.config/menus/applications-merged/user-menulibre-ham-radio.menu
fi
# These cause duplicated multimedia and internet menus
if [ -f ~/.config/menus/applications-merged/user-xfce-multimedia.menu ]; then
	rm ~/.config/menus/applications-merged/user-xfce-multimedia.menu   
fi
if [ -f ~/.config/menus/applications-merged/user-xfce-network.menu ]; then
	rm ~/.config/menus/applications-merged/user-xfce-network.menu   
fi

# Remove brltty
sudo apt remove -y brltty

# Install HamLib
sudo apt -y install libhamlib4 libhamlib-utils

# make sure all wireless connections are set as available for all users (permission blank) so avaialable at boot!
interfaces=$(nmcli -t c)
while IFS= read -r line
do
	name="$(cut -f1 -d: <<< $line)"
	type="$(echo $line | cut -f3 -d:)"
	if [ "$type" == "802-11-wireless" ]; then
		sudo nmcli con modify "$name" connection.permissions ""
	fi
done <<< "${interfaces}"

# Add GPS support in chrony if not already done
CHRONYCHK=$(grep "refclock SHM 0 offset 0.5 delay 0.2 refid NMEA" /etc/chrony/chrony.conf)
	if [ -z "$CHRONYCHK" ]; then
		echo "refclock SHM 0 offset 0.5 delay 0.2 refid NMEA" | sudo tee -a /etc/chrony/chrony.conf
	fi


# process selected apps from YAD menu
while IFS= read -r line
do
	check=$(echo $line | cut -f1 -d'|' )
	name=$(echo $line | cut -f2 -d'|' )
	if [ $check = TRUE ]; then
		prefix="install_"
		# execute function to install this app
		$prefix$name
	fi
done <<< "${selected_options}"

sleep 10
