#!/bin/bash

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

MYPATH="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
BASE=${MYPATH}/base.txt
FUNCTIONS=${MYPATH}/functions
ADDITIONAL=${MYPATH}/additional.txt
UTILITY=${MYPATH}/utility.txt
FLSUITE=${MYPATH}/flsuite.txt
CONFIG=${MYPATH}/config
LOGO=${MYPATH}/logo.png
TEMPCRON=${MYPATH}/cron.tmp
VERSION=$(grep "version=" ${MYPATH}/changelog | sed 's/version=//')
DATE=$(date)
UPDATEFILE=/run/user/$UID/bapupdate.txt

FINISH() {
	if [ -f "${BASE}" ]; then
		rm ${BASE}
	fi

	if [ -f "${ADDITIONAL}" ]; then
		rm ${ADDITIONAL}
	fi

	if [ -f "${FLSUITE}" ]; then
		rm ${FLSUITE}
	fi

	if [ -f "${UTILITY}" ]; then
		rm ${UTILITY}
	fi
}

trap FINISH EXIT

#####################################
#	Old OS Check
#####################################
V_ID=$(grep VERSION_ID /etc/os-release | sed 's/VERSION_ID="//;s/"//')

if [ "$V_ID" -le 10 ]; then
NOTICEPATH=/run/user/$UID

cat <<EOF >${NOTICEPATH}/intro.txt
Build a Pi 3.2.0 and later does not support
RaspiOS Buster or earlier versions of RaspiOS.
You should consider upgrading to RaspiOS 11
(Bullseye). By clicking ok you will be moved
to the last version of Build a Pi (3.1.4) that 
supports Pi OS Buster. Please note there are 
no plans to update Build a Pi for Buster going 
forward.  In other words, you are on your own 
if it is broke and you are still running Pi OS
10 (Buster).

EOF

INTRO=$(yad --width=600 --height=300 --text-align=center --center --title="Out of Date OS Detected!" --show-uri \
	--image ${LOGO} --window-icon=${LOGO} --image-on-top --separator="|" --item-separator="|" \
	--text-info \
	--button="OK":1 <${NOTICEPATH}/intro.txt \
	--button="Exit":2 \
	>/dev/null 2>&1)
	BUT=$?
	echo $BUT
	if [ $BUT = 2 ] || [ $BUT = 252 ]; then
	exit
	fi
	rm ${NOTICEPATH}/intro.txt
	cd $HOME/pi-build
	git checkout buster 
	bash build-a-pi & exit
fi

#####################################
#	end Old OS Check
#####################################

#remove temp dir if exist
#fix issue 108 https://github.com/km4ack/pi-build/issues/108
#Thanks to N5RKS for finding the bug
if [ -d ${HOME}/pi-build/temp ]; then
	rm -rf "${HOME}/pi-build/temp"
fi

#####################################
#	Create autostart dir
#used to autostart conky at boot
#####################################
mkdir -p ${HOME}/.config/autostart

#Check for BAP updates
#Check for build a pi updates
echo "Checking for Build a Pi updates"
CURRENT=$(head -1 ${MYPATH}/changelog | sed s'/version=//')

LATEST=$(curl -s https://raw.githubusercontent.com/km4ack/pi-build/master/changelog | tac | tac | head -1 | sed 's/version=//')

if (($(echo "$LATEST $CURRENT" | awk '{print ($1 > $2)}'))); then
	cat <<EOF >${MYPATH}/updatebap.txt
Build a Pi update available. Current version is $CURRENT and
the lateest version is $LATEST. Would you like to update?

Change log - https://github.com/km4ack/pi-build/blob/master/changelog
EOF
	BAP=$(
		yad --width=650 --height=250 --text-align=center --center --title="Build-a-Pi" --show-uri \
			--image ${LOGO} --window-icon=${LOGO} --image-on-top --separator="|" --item-separator="|" \
			--text-info \
			--button="Yes":2 \
			--button="No":3 <${MYPATH}/updatebap.txt

	)
	BUT=$?
	echo ${BUT}
	##########
	if [ ${BUT} = 252 ]; then
		exit
	elif [ ${BUT} = 2 ]; then
		wget -q --tries=5 --timeout=10 --spider http://google.com #| yad --center --progress --pulsate --timeout-indicator=top --auto-close --no-buttons --text="Checking internet connection"
		if [[ $? -eq 1 ]]; then
			yad --center --timeout=3 --timeout-indicator=top --no-buttons --text="You are not connected to the internet"
			exit
		fi
		echo "Updating Build a Pi to $LATEST"
		mv ${MYPATH}/config ${HOME}/Documents/config.bap
		rm -rf "${MYPATH}"
		cd ~ || ! echo "Failure"
		git clone https://github.com/km4ack/pi-build.git
		mv ${HOME}/Documents/config.bap ${MYPATH}/config

		cat <<EOF >${MYPATH}/updatebap.txt
Build a Pi has been updated to $LATEST. Please restart Build a Pi.
EOF
		BAP=$(
			yad --width=650 --height=250 --text-align=center --center --title="Build-a-Pi" --show-uri \
				--image ${LOGO} --window-icon=${LOGO} --image-on-top --separator="|" --item-separator="|" \
				--text-info \
				--button="OK":2 <${MYPATH}/updatebap.txt
		)
		BUT=$?
		exit 0
	fi
##########
fi
rm ${MYPATH}/updatebap.txt >>/dev/null 2>&1
rm ${MYPATH}/complete.txt >>/dev/null 2>&1
clear

#####################################
#	Patch Check
#####################################

#This check first looks at the README.md file to see if the PATCH var is YES.
#If PATCH=YES, then it looks to see if the patches that are available have 
#been applied previously. If so, it skips the patch screen. If not, it gives
#the user an option to install the patch(es).

PATCHCHECK=$(curl -s https://raw.githubusercontent.com/km4ack/pi-build/dev/patch/README.md | grep PATCH= | sed 's/PATCH=//')

if [ ${PATCHCHECK} = "YES" ]; then
#Setup temp directory for BAP patches and download patches
echo "##########################################################"
echo "#Checking for available patches that haven't been applied#"
echo "##########################################################"
cd /run/user/$UID
git init pi-build
cd pi-build
git remote add -f origin https://github.com/km4ack/pi-build.git
git config core.sparseCheckout true
echo "/patch" >> .git/info/sparse-checkout
git pull origin dev

FILES=$(ls -I README.md /run/user/$UID/pi-build/patch)

#check if available patches have already been applied to BAP
for i in $FILES; do

NAME=$(grep PATCHNAME= /run/user/$UID/pi-build/patch/$i | sed 's/PATCHNAME=//')
RB=$(grep $NAME $HOME/.config/patch)
if [ -z $RB ]; then
echo "$NAME" >> /run/user/$UID/avail-patch.txt
fi
done
#end check

	if [ -f /run/user/$UID/avail-patch.txt ]; then
	rm /run/user/$UID/avail-patch.txt

cat <<EOF >${MYPATH}/patch.txt
One or more patch scripts are currently
available for Build a Pi. Full description
of each available patch can be found at
https://github.com/km4ack/pi-build/tree/dev/patch

Would you like to review/apply 
available patch scripts?
EOF

INTRO=$(yad --width=650 --height=300 --text-align=center --center --title="Build-a-Pi Patch Tool" --show-uri \
	--image ${LOGO} --window-icon=${LOGO} --image-on-top --separator="|" --item-separator="|" --text="Build-a-Pi Patch Tool" \
	--text-info \
	--button="Yes":1 \
	--button="No":2 <${MYPATH}/patch.txt \
	>/dev/null 2>&1)
BUT=$?

		if [ ${BUT} = 252 ]; then
		echo "Button ${BUT} pressed"
		rm ${MYPATH}/patch.txt
		rm -rf /run/user/$UID/pi-build
		exit
		elif [ ${BUT} = 1 ]; then
		echo "Button ${BUT} pressed"
		rm ${MYPATH}/patch.txt
		lxterminal -e bash $HOME/pi-build/patch-menu && exit
		elif [ ${BUT} = 2 ]; then
		echo "Button ${BUT} pressed"
		rm ${MYPATH}/patch.txt
		echo "user declined patch updates continuing with Build a Pi update"
		rm -rf /run/user/$UID/pi-build
		fi
	else
	rm -rf /run/user/$UID/pi-build	
	fi
fi


	
#Scan system for updated applications
yad --width=550 --height=250 --text-align=center --center --title="Update" \
	--image ${LOGO} --window-icon=${LOGO} --image-on-top --separator="|" --item-separator="|" \
	--text="<b>Version $VERSION</b>\r\r\r\rFirst we need to scan the system to see what is installed, \
then check for updates on the web. This should take less than a minute. Ready when you are." \
	--button="Exit":1 \
	--button="Start Scan":2
BUT=$?
if [ ${BUT} = 252 ] || [ ${BUT} = 1 ]; then
	exit
fi

#install bc if not installed
if ! hash bc >/dev/null; then
	sudo apt install -y bc
fi


#Run the app check script
bash $MYPATH/app-check

#####################################
#	Get User Call
#####################################
CALL() {
	source ${MYPATH}/config
	INFO=$(yad --form --width=420 --text-align=center --center --title="Build-a-Pi" \
		--image ${LOGO} --window-icon=${LOGO} --image-on-top --separator="|" --item-separator="|" \
		--text="<b>version ${VERSION}</b>" \
		--field="Call Sign*" "${CALL}" \
		--field="<b>* Required</b>":LBL \
		--button="Continue":2)
	BUT=$?
	if [ ${BUT} = 252 ]; then
		exit
	fi
}
CALL
CALL=$(echo $INFO | awk -F "|" '{print $1}')
CALL=${CALL^^}

echo "CALL=${CALL}" >${CONFIG}

#Verify call not empty
if [ -z "${CALL}" ]; then
	yad --form --width=420 --text-align=center --center --title="Build-a-Pi" --text-align=center \
		--image ${LOGO} --window-icon=${LOGO} --image-on-top --separator="|" --item-separator="|" \
		--text="<b>Call Can't be Blank</b>" \
		--button=gtk-ok
	CALL
fi

#----------------------------------------------------#
#			BASE APP MENU
#----------------------------------------------------#
source $UPDATEFILE
yad --center --list --checklist --width=600 --height=600 --separator="" \
	--image ${LOGO} --column=Check --column=App --column=status --column=description --print-column=2 \
	--window-icon=${LOGO} --image-on-top --text-align=center \
	--text="<big><big><b>Base Apps</b></big></big>" --title="Update" \
	false "HAMLIB" "$RIG" "Rig Control" \
	false "HOTSPOT" "$HOTSPOT" "Hot Spot Generator for Portable Ops" \
	false "HSTOOLS" "$HSTOOLS" "Tools to Manage HotSpot" \
	false "GPS" "${GPS}" "GPS Software" \
	false "GPSUPDATE" "${GPSUPDATE}" "Tool to Manage GPS Devices" \
	false "ARDOP" "$ARDOP" "Mode for HF" \
	false "ARDOPGUI" "$ARDOPGUI" "GUI for ARDOP" \
	false "VARA" "$VARA" "VARA Modem - <b>Pi 4 Required</b>" \
	false "DIREWOLF" "$DIRE" "Software TNC" \
	false "AX25" "$AX25" "Data Link Layer Protocol" \
	false "PULSE" "$PULSE" "Sound server" \
	--button="Exit":1 \
	--button="Next":2 >${BASE}
BUT=$?
if [ ${BUT} = 1 ] || [ ${BUT} = 252 ]; then
	exit
fi

#If VARA is chosen, make sure we have a Pi 4 to work with. 
#As of 02OCT2022 the VARA installer only works with the Pi 4.
VARA_CHK=$(grep VARA ${BASE})
if [ -n "$VARA_CHK" ]; then
	FREEMEM=$(free -m | grep Mem: | awk '{ print $2 }')
	if [ $FREEMEM -lt 1500 ]; then
	echo "Not enough memory available"
	yad --form --width=500 --text-align=center --center --title="Build-a-Pi" --text-align=center \
	--image ${LOGO} --window-icon=${LOGO} --image-on-top --separator="|" --item-separator="|" \
	--text="<b>Not enough memory</b>\rVARA requires a Pi 4.\r\rVARA will not be installed during the build." \
	--button=gtk-ok
	sed -i 's/VARA//;/^$/d' ${BASE}
	fi

fi

#############################################################
#check if hotspot is chosen for install & get info if needed#
#############################################################
HS=$(cat ${BASE} | grep HOTSPOT)
if [ -n "$HS" ]; then
	HSINFO() {
		#unblock wifi
		sudo rfkill unblock all >/dev/null 2>&1
		#bring wifi up
		sudo ifconfig wlan0 up
		#LIST=$(sudo iw dev "wlan0" scan ap-force | egrep "^BSS|SSID:" | grep SSID: | sed 's/SSID://' | awk '{ print $1 }')
		#LIST=$(echo $LIST | sed 's/ /|/g')
		#Thanks to https://github.com/kuperman for fixing wifi space issue with line below.
		LIST=$(sudo iw dev "wlan0" scan ap-force | sed -ne 's/^.*SSID: \(..*\)/\1/p' | sort | uniq | paste -sd '|')

		HSINFO=$(yad --center --form --width=400 --height=400 --separator="|" --item-separator="|" \
			--image ${LOGO} --column=Check --column=App --column=Description \
			--window-icon=${LOGO} --image-on-top --text-align=center \
			--text="<b>HotSpot Information\r\rPlease enter the information\rbelow \
for the Hot Spot\r</b>NOTE: The last field is the password for the hotspot. You will use this password to \
connect to your Pi when it is in hotspot mode <b>This password can only contain letters and numbers</b>" \
			--title="Build-a-Pi" \
			--field="Home Wifi SSID":CB "${LIST}" \
			--field="Home Wifi Password":H \
			--field="Hot Spot Password" \
			--button="Exit":1 \
			--button="Continue":2 \
			--button="Refresh Wifi":3)
		#} 					THIS IS WHERE ORIGINAL FUNCTION STOPPED################
		#HSINFO					SEE COMMENT PREVIOUS LINE
		BUT=$?
		if [ ${BUT} = 3 ]; then
			HSINFO #Call HSINFO function
		fi

		if [ ${BUT} = 252 ] || [ ${BUT} = 1 ]; then
			exit
		fi
	} #THIS IS NEW FUNCTION END FOR TESTING####################

	HSINFO
fi
SHACKSSID=$(echo $HSINFO | awk -F "|" '{print $1}')
SHACKPASS=$(echo $HSINFO | awk -F "|" '{print $2}')
HSPASS=$(echo $HSINFO | awk -F "|" '{print $3}')

#Check password length
if [ -n "$HS" ]; then
	COUNT=${#HSPASS}
	if [ $COUNT -lt 8 ]; then
		yad --center --form --width=300 --height=200 --separator="|" \
			--image ${LOGO} --column=Check --column=App --column=Description \
			--window-icon=${LOGO} --image-on-top --text-align=center \
			--text="<b>Hotspot password has to be 8-63 characters</b>" --title="Build-a-Pi" \
			--button=gtk-ok
		HSINFO
	fi
fi

echo "SHACKSSID=${SHACKSSID}" >>${CONFIG}
echo "SHACKPASS=${SHACKPASS}" >>${CONFIG}
echo "HSPASS=${HSPASS}" >>${CONFIG}

###################################
#CHECK IF GPS IS CHOSEN TO INSTALL#
###################################
GPSINSTALL=$(cat ${BASE} | grep GPS)
if [ -n "${GPSINSTALL}" ]; then

	yad --center --height="300" --width="300" --form --separator="|" --item-separator="|" --title="GPS" \
		--image ${LOGO} --window-icon=${LOGO} --image-on-top \
		--text="\r\r\r\r\r<b><big>Connect your GPS to the pi</big></b>" \
		--button="Exit":1 \
		--button="Continue":2

	BUT=$?
	if [ ${BUT} = 1 ] || [ ${BUT} = 252 ]; then
		exit
	fi

	USB=$(ls /dev/serial/by-id)
	USB=$(echo $USB | sed "s/\s/|/g")

	GPS=$(yad --center --height="600" --width="300" --form --separator="|" --item-separator="|" --title="GPS" \
		--image ${LOGO} --window-icon=${LOGO} --image-on-top \
		--text="Choose Your GPS" \
		--field="GPS":CB "$USB")
	BUT=$?
	if [ ${BUT} = 252 ] || [ ${BUT} = 1 ]; then
		echo exiting
		exit
	fi

	GPS=$(echo ${GPS} | awk -F "|" '{print $1}')
	GPS=/dev/serial/by-id/${GPS}
	echo "GPS=${GPS}" >>${CONFIG}
fi

#----------------------------------------------------#
#		FLSUITE APP MENU
#----------------------------------------------------#
source $UPDATEFILE
yad --center --list --checklist --width=600 --height=600 --separator="" \
	--image ${LOGO} --column=Check --column=App --column=status --column=description --print-column=2 \
	--window-icon=${LOGO} --image-on-top --text-align=center \
	--text="<big><big><b>FLDIGI Suite</b></big></big>" --title="Update" \
	false "FLRIG" "${FLRIG}" "Rig Control GUI" \
	false "FLDIGI" "${FLDIGI}" "Digital Software" \
	false "FLAMP" "${FLAMP}" "File Transfer Program" \
	false "FLNET" "${FLNET}" "Net Control Software" \
	false "FLMSG" "${FLMSG}" "Form Manager" \
	false "FLWRAP" "${FLWRAP}" "File Encapsulation" \
	--button="Exit":1 \
	--button="Next":2 >${FLSUITE}
BUT=$?
if [ ${BUT} = 1 ] || [ ${BUT} = 252 ]; then
	exit
fi
#----------------------------------------------------#
#		HAM APP MENU
#----------------------------------------------------#
source $UPDATEFILE
yad --center --list --checklist --width=600 --height=600 --separator="" \
	--image ${LOGO} --column=Check --column=App --column=status --column=description --print-column=2 \
	--window-icon=${LOGO} --image-on-top --text-align=center \
	--text="<big><big><b>HAM Apps</b></big></big>" --title="Update" \
	false "PAT" "$PAT" "Radio Email Application" \
	false "PAT-MENU" "$PATMENU" "Control for Pat Winlink" \
	false "CHIRP" "$CHIRP" "Program Radios" \
	false "GARIM" "$GARIM" "File Transfer Program " \
	false "VARIM" "$VARIM" "Radio Chat VARA" \
	false "M0IAX" "$M0IAX" "Tools for JS8Call messages" \
	false "CONKY" "$CONKY" "System Information Display" \
	false "WSJTX" "$FT8" "Weak signal digital mode software" \
	false "JS8CALL" "$JS8" "Weak signal digital mode software" \
	false "REPEAT" "$REPEAT" "Repeater Directory" \
	false "XASTIR" "$XASTIR" "APRS Client" \
	false "YAAC" "$YAAC" "Yet Another APRS Client" \
	false "PI-APRS" "$PIAPRS" "APRS Messaging Client" \
	false "PYQSO" "$PYQSO" "Logging Software" \
	false "HAMRS" "$HAMRS" "Logging Software" \
	false "CQRLOG" "$CQRLOG" "Logging Software" \
	false "QSSTV" "$QSSTV" "Slow scan TV" \
	false "GRIDTRACKER" "$GRIDTRACK" "Track grids in WSJTX" \
	false "HAMCLOCK" "$HAMCLOCK" "Clock for Ham Radio Ops" \
	false "PROPAGATION" "$PROP" "Propagation prediction" \
	false "EES" "$EES" "KM4ACK Emergency Email Server" \
	false "GPREDICT" "$GPREDICT" "Satellite Tracking" \
	false "TQSL" "$TQSL" "LOTW Software" \
	false "GRIDCALC" "$GRIDCALC" "Grid Calculation Software" \
	--button="Exit":1 \
	--button="Next":2 >${ADDITIONAL}
BUT=$?
if [ ${BUT} = 1 ] || [ ${BUT} = 252 ]; then
	exit
fi

#check if hamclock is being installed
HCCHECK=$(cat ${ADDITIONAL} | grep HAMCLOCK)
if [ -n "$HCCHECK" ]; then

	HC=$(yad --form --width=420 --text-align=center --center --title="Build-a-Pi" \
		--image ${LOGO} --window-icon=${LOGO} --image-on-top --separator="|" --item-separator="|" \
		--text="<b>version $VERSION</b>" \
		--field="Ham Clock Size":CB "SMALL|LARGE" \
		--button="Continue":2)
	HC=$(echo $HC | awk -F "|" '{print $1}')
	sed -i 's/HAMCLOCK//' ${ADDITIONAL}
	echo $HC >>${ADDITIONAL}
fi


PATCHECK=$(cat ${ADDITIONAL} | grep PAT)
if [ -n "$PATCHECK" ]; then
	INFO=$(yad --form --width=420 --text-align=center --center --title="Build-a-Pi" \
		--image ${LOGO} --window-icon=${LOGO} --image-on-top --separator="|" --item-separator="|" \
		--text="<b>version $VERSION</b>" \
		--field="Six Character Grid Square" "$GRID" \
		--field="Winlink Password":H \
		--field="<b>Password is case sensitive</b>":LBL \
		--button="Continue":2)
	GRID=$(echo $INFO | awk -F "|" '{print $1}')
	GRID=${GRID^^}
	WL2KPASS=$(echo $INFO | awk -F "|" '{print $2}')
	echo "GRID=$GRID" >>${CONFIG}
	echo "WL2KPASS=\"$WL2KPASS\"" >>${CONFIG}

fi

#----------------------------------------------------#
#		UTILITIES MENU
#----------------------------------------------------#
source $UPDATEFILE
yad --center --list --checklist --width=600 --height=600 --separator="" \
	--image ${LOGO} --column=Check --column=App --column=status --column=description --print-column=2 \
	--window-icon=${LOGO} --image-on-top --text-align=center \
	--text="<big><big><b>UTILITIES</b></big></big>" --title="Update" \
	false "DIPOLE" "$DIPOLE" "Dipole Calculator" \
	false "PACKETSEARCH" "$PACKETSEARCH" "Winlink Packet Tool" \
	false "CALLSIGN" "${CALLSIGN}" "Call Sign Lookup Utility" \
	false "TEMPCONVERT" "$TEMPCONVERT" "Temperature Converter" \
	false "HDOCS" "$HDOCS" "Reference Materials PDFs" \
	false "GPARTED" "$GPARTED" "Disk Utility Application" \
	false "RTC" "$RTC" "Real Time Clock" \
	false "SHOWLOG" "$SHOWLOG" "Log File Viewer" \
	false "PISTATS" "$PISTATS" "Pi3/4 Stats Monitor" \
	false "TELNET" "$TEL" "Telnet Protocol" \
	false "PITERM" "$PITERM" "PiQTermTCP Terminal Program" \
	false "QTSOUND" "$QTSOUND" "PiQtSoundModem" \
	false "SECURITY" "$SECURITY" "File Encryption Software" \
	false "YGATE" "$YGATE" "Yaesu APRS Software" \
	false "BPQ" "$BPQ" "LinBPQ Software" \
	false "BATT" "$BATT" "Battery Test Script" \
	false "VNC" "$VNC" "VNC Viewer Application" \
	false "XYGRIB" "$XYGRIB" "Grib file viewer" \
	--button="Exit":1 \
	--button="Install/Update Selected":2 >${UTILITY}
BUT=$?
if [ ${BUT} = 1 ] || [ ${BUT} = 252 ]; then
	exit
fi

#check and exit if nothing selected
CKBASE=$(cat ${BASE})
CKFL=$(cat ${FLSUITE})
CKADD=$(cat ${ADDITIONAL})
CKUTIL=$(cat ${UTILITY})
if [ -z "$CKBASE" ] && [ -z "$CKFL" ] && [ -z "$CKADD" ] && [ -z "$CKUTIL" ]; then
	rm ${BASE} ${FLSUITE} ${ADDITIONAL} ${UTILITY} >/dev/null 2>&1
	yad --width=550 --height=250 --text-align=center --center --title="Update" \
		--image ${LOGO} --window-icon=${LOGO} --image-on-top --separator="|" --item-separator="|" \
		--text="\r\r\r\r<b>Nothing selected for install/update</b>" \
		--button="CLOSE":1
	exit
fi

#backup crontab
crontab -l >${TEMPCRON}
echo "@reboot sleep 10 && export DISPLAY=:0 && ${MYPATH}/.complete" >>${TEMPCRON}
#update/upgrade the system
sudo apt-get -y update
sudo apt-get -y upgrade
sudo apt -y full-upgrade

#create bap repair tool if it doesn't exist
if [ ! -f /usr/local/bin/repair-bap ]; then

cat <<EOF > /run/user/$UID/repair-bap
#!/bin/bash

if [ ! -f $HOME/pi-build/update ]; then
echo "################################"
echo "#  BAP update tool not found.  #"
echo "#  Repairing, please stand by  #"
echo "################################"
cd $HOME
git clone https://github.com/km4ack/pi-build.git || echo "Could not connect to Github. Check your internet and try again"
echo "Repair complete. Run the Build a Pi update tool using the shortcut in the Pi menu"
else
clear;echo;echo
echo "Update tool is present on the system."
fi
EOF
chmod +x /run/user/$UID/repair-bap
sudo mv /run/user/$UID/repair-bap /usr/local/bin/

fi

#####################################
#	Install Base Apps
#####################################
touch ${HOME}/.config/KM4ACK
echo "UPDATE=\"ran $DATE Version $VERSION\"" >> ${HOME}/.config/KM4ACK
while read i; do
	source ${FUNCTIONS}/base.function
	$i
done <${BASE}

#####################################
#	Install FLSUITE
#####################################
source ${FUNCTIONS}/flsuite.function
#perform memory increase if needed
CHECKFL=$(cat ${MYPATH}/flsuite.txt)
if [ -n "$CHECKFL" ]; then
	FLSTART
fi

touch ${HOME}/.config/KM4ACK
while read i; do
	source ${FUNCTIONS}/flsuite.function
	$i
done <${FLSUITE}

source ${FUNCTIONS}/flsuite.function
if [ -n "$CHECKFL" ]; then
	FLSTOP
fi

#####################################
#	Install ADDITIONAL Apps
#####################################
while read i; do
	source ${FUNCTIONS}/additional.function
	$i
done <${ADDITIONAL}

#####################################
#	Install KM4ACK Utilites
#####################################
while read i; do
	source ${FUNCTIONS}/utility.function
	$i
done <${UTILITY}

#create new menu subcategories. One for FLDIGI Suite and
#one for Build a Pi.
bash ${HOME}/pi-build/menu-update

#####################################
#	END CLEANUP
#####################################
#Remove temp files
rm ${BASE} ${ADDITIONAL} ${UTILITY} ${FLSUITE} >/dev/null 2>&1

#remove libham (rigctl) installed from apt
#since it conflicts with hamlib installed from source
sudo apt purge -y libhamlib4

#restore crontab
crontab ${TEMPCRON}
rm ${TEMPCRON}

#reboot when done
yad --width=400 --height=200 --title="Reboot" --image ${LOGO} \
	--text-align=center --skip-taskbar --image-on-top \
	--wrap --center --window-icon=${LOGO} \
	--undecorated --text="<big><big><big><b>Update Finished \rReboot Required</b></big></big></big>\r\r" \
	--button="Reboot Now":0 \
	--button="Exit":1
BUT=$(echo $?)

if [ ${BUT} = 0 ]; then
	echo rebooting
	sudo reboot
elif [ ${BUT} = 1 ]; then
	exit
fi
