#!/bin/bash

FLAG=0
checkout=0
BULLSEYE=0
UPDATE=0
NETWORK=1

FILE=/home/pi/CubeSatSim/cubesatsim  # code has already been compiled
if [ -f "$FILE" ]; then

	UPDATE=1

	echo -e "\nUpdate script for CubeSatSim v2.3\n"

	echo "You should restart when this update completes with command:"
	echo "sudo reboot now"
	echo

	sudo rm /home/pi/CubeSatSim/telem.wav &>/dev/null
	sudo rm /home/pi/CubeSatSim/t.txt  &>/dev/null
	sudo rm /home/pi/CubeSatSim/uptime &>/dev/null

	if [ -z "$1" ] ; then
		checkout=0
	else
		checkout=1
		branch="$1"
		echo -n "changing to branch "
		echo $branch
		FLAG=1
	fi
	
	if [ "$2" = "n" ] ; then
		noreboot=1
	else
		noreboot=0
	fi

else

	echo -e "\nInstallation script for CubeSatSim v2.3\n"

	echo "You should restart when this install completes with command:"
	echo "sudo reboot now"
	echo

	touch /home/pi/CubeSatSim/command_control_direwolf

    echo "creating $FILE"
    echo "AMSAT 0 0 0 no 3 434.9 435 no 0 0 no 60 no" > /home/pi/CubeSatSim/sim.cfg

	echo "434900000 435000000" > frequency.txt

	cp /home/pi/CubeSatSim/hotspot_ini /home/pi/CubeSatSim/hotspot.ini

	/home/pi/CubeSatSim/config -c -n

	/home/pi/CubeSatSim/config -l -n

fi

FILE=/home/pi/CubeSatSim/hotspot.ini
if [ ! -f "$FILE" ]; then
	echo "Creating hotspot.ini configuration file. You can edit it to change Wi-Fi hotspot options"
	cp /home/pi/CubeSatSim/hotspot_ini /home/pi/CubeSatSim/hotspot.ini
fi

if [[ $(grep 'bullseye' /etc/os-release) ]]; then

	BULLSEYE=1

    echo "Debian 11 (Bullseye) detected"

  	sudo cp /boot/config.txt /boot/config.txt.0

	  sudo cp /boot/cmdline.txt /boot/cmdline.txt.0
	
	  sudo raspi-config nonint do_i2c 0
	
	  sudo raspi-config nonint do_camera 0
	
	  sudo raspi-config nonint do_legacy 0
	  
	  sudo sed -i 's/console=serial0,115200 //g' /boot/cmdline.txt
	
#	  sudo sed -i 's/console=tty1 r/console=tty1 maxcpus=2 r/g' /boot/cmdline.txt # single core if Pi Zero 2
##	  sudo sed -i 's/console=tty1 maxcpus=1 r/console=tty1 r/g' /boot/cmdline.txt 
	
#	  sudo sed -i 's/maxcpus=1/maxcpus=2/g' /boot/cmdline.txt # single core if Pi Zero 2
	
	  sudo sed -i 's/#dtparam=i2c_arm=on/dtparam=i2c_arm=on/g' /boot/config.txt
	  
	  if [[ $(grep 'dtoverlay=i2c-gpio,bus=3,i2c_gpio_delay_us=1,i2c_gpio_sda=23,i2c_gpio_scl=24' /boot/config.txt) ]]; then
	    echo "dtoverlay=i2c-gpio already in /boot/config.txt"
	  else
	    echo "adding dtoverlay=i2c-gpio to /boot/config.txt"
	    sudo sh -c 'echo "\ndtoverlay=i2c-gpio,bus=3,i2c_gpio_delay_us=1,i2c_gpio_sda=23,i2c_gpio_scl=24" >> /boot/config.txt'
	  fi
	
	  if [[ $(grep 'enable_uart=1' /boot/config.txt) ]]; then
	    echo "enable_uart=1 already in /boot/config.txt"
	  else
	    echo "adding enable_uart=1 to /boot/config.txt"
	    sudo sh -c 'echo "\nenable_uart=1" >> /boot/config.txt'
	  fi
	  
	  if [[ $(grep 'dtoverlay=disable-bt' /boot/config.txt) ]]; then
	    echo "dtoverlay=disable-bt already in /boot/config.txt"
	  else
	    echo "adding dtoverlay=disable-bt to /boot/config.txt"
	    sudo sh -c 'echo "\ndtoverlay=disable-bt" >> /boot/config.txt'
	  fi
	  
	  if [[ $(grep 'dtoverlay=dwc2' /boot/config.txt) ]]; then
	    echo "dtoverlay=dwc2 aalready in /boot/config.txt"
	  else
	    echo "adding dtoverlay=dwc2 to /boot/config.txt"
	    sudo sh -c 'echo "\ndtoverlay=dwc2" >> /boot/config.txt'
	  fi
	
	  if [[ $(grep 'modules-load=dwc2,g_ether' /boot/cmdline.txt) ]]; then
	    echo "modules-load=dwc2,g_ether already in /boot/cmdline.txt"
	  else
	    echo "adding modules-load=dwc2,g_ether to /boot/cmdline.txt"
	    sudo sed -i 's/ rootwait/ rootwait modules-load=dwc2,g_ether/g' /boot/cmdline.txt
	  fi
	  
	  if [[ $(grep 'dtparam=audio=on' /boot/config.txt) ]]; then
	    echo "dtparam=audio=on already in /boot/config.txt"
	  else
	    echo "adding dtparam=audio=on to /boot/config.txt"
	    sudo sh -c 'echo "\ndtparam=audio=on" >> /boot/config.txt'
	  fi
	
	  if [[ $(grep 'dtoverlay=audremap,enable_jack=on' /boot/config.txt) ]]; then
	    echo "dtoverlay=audremap,enable_jack=on already in /boot/config.txt"
	  else
	    echo "adding dtoverlay=audremap,enable_jack=on to /boot/config.txt"
	    sudo sh -c 'echo "\ndtoverlay=audremap,enable_jack=on" >> /boot/config.txt'
	  fi
	
	  if [[ $(grep 'dtoverlay=pwm,pin=18,func=2' /boot/config.txt) ]]; then
	    echo "dtoverlay=pwm,pin=18,func=2 already in /boot/config.txt"
	  else
	    echo "adding overlay=pwm,pin=18,func=2 to /boot/config.txt"
	    sudo sh -c 'echo "\ndtoverlay=pwm,pin=18,func=2" >> /boot/config.txt'
	  fi
	
	  if [[ $(grep 'disable_splash=1' /boot/config.txt) ]]; then
	    echo "disable_splash=1 already in /boot/config.txt"
	  else
	    echo "adding disable_splash=1 to /boot/config.txt"
	    sudo sh -c 'echo "\ndisable_splash=1" >> /boot/config.txt'
	  fi
	
	  if [[ $(grep 'boot_delay=0' /boot/config.txt) ]]; then
	    echo "boot_delay=0 already in /boot/config.txt"
	  else
	    echo "adding boot_delay=0 to /boot/config.txt"
	    sudo sh -c 'echo "\nboot_delay=0" >> /boot/config.txt'
	  fi
	
	  if ! grep -q force_turbo=1 /boot/config.txt ; then sudo sh -c 'echo "force_turbo=1" >> /boot/config.txt'; fi
	
	  sudo sh -c 'echo "\n" >> /boot/config.txt'

	  if [[ $(sudo systemctl is-active NetworkManager | grep inactive) ]]; then
			echo
	    	echo "NetworkManager is inactive"
			echo
	    	echo "In order to use the Wi-Fi Hotspot, NetworkManager needs to be enabled and configured."
			echo
			echo "Do you want to enable NetworkManager and re-configure your Wi-Fi (y/n) "
			read choice
			echo
			if [ "$choice" = "y" ] || [ "$choice" = "yes" ]  ; then
				NETWORK=0

#				sudo sed -i 's/managed=false/managed=true/g' /etc/NetworkManager/NetworkManager.conf # allow nmcli to manage WiFi
#				sudo systemctl disable dhcpcd
#				sudo systemctl enable NetworkManager
#				sudo systemctl start NetworkManager
#				sudo nmcli dev wifi connect "$ssid" password "$password"

				echo "Enter your Wi-Fi SSID"
				read ssid
				echo "Enter your Wi-Fi password"
				read password

				echo
				echo "Wi-Fi will be updated at the end of this install/update.  You will need to log back in."
				echo
				sleep 5
			else
				echo "Not enabling NetworkManager. Wi-Fi Hotspot feature will not be available."
			fi
	  fi

	  FILE=/usr/bin/ttyd
	  if [ -f "$FILE" ]; then
    	  echo "$FILE exists."
	  else
	      cd /tmp
		  wget https://github.com/tsl0922/ttyd/releases/download/1.7.7/ttyd.armhf
		  chmod +x ttyd.armhf
	      sudo cp ttyd.armhf $FILE
	  fi

  fi

if [[ $(grep 'bookworm' /etc/os-release) ]]; then
	
	echo "Debian 12 (Bookworm) detected"

	sudo cp /boot/firmware/config.txt /boot/firmware/config.txt.0
	
	sudo cp /boot/firmware/cmdline.txt /boot/firmware/cmdline.txt.0
	
	sudo raspi-config nonint do_i2c 0
	
	sudo raspi-config nonint do_camera 0
	
	sudo raspi-config nonint do_legacy 0
	
	  sudo sed -i 's/console=serial0,115200 //g' /boot/firmware/cmdline.txt
	
#	  sudo sed -i 's/console=tty1 r/console=tty1 maxcpus=2 r/g' /boot/firmware/cmdline.txt # single core if Pi Zero 2
##	  sudo sed -i 's/console=tty1 maxcpus=1 r/console=tty1 r/g' /boot/firmware/cmdline.txt 
	
#	  sudo sed -i 's/maxcpus=1/maxcpus=2/g' /boot/firmware/cmdline.txt # single core if Pi Zero 2
	
	  sudo sed -i 's/#dtparam=i2c_arm=on/dtparam=i2c_arm=on/g' /boot/firmware/config.txt

	  sudo sed -i 's/#dtoverlay=vc4-fkms-v3d/dtoverlay=vc4-fkms-v3d/g' /boot/firmware/config.txt
	  sudo sed -i 's/#dtoverlay=vc4-kms-v3d/dtoverlay=vc4-kms-v3d/g' /boot/firmware/config.txt

	  
	  if [[ $(grep 'dtoverlay=i2c-gpio,bus=3,i2c_gpio_delay_us=1,i2c_gpio_sda=23,i2c_gpio_scl=24' /boot/firmware/config.txt) ]]; then
	    echo "dtoverlay=i2c-gpio already in /boot/firmware/config.txt"
	  else
	    echo "adding dtoverlay=i2c-gpio to /boot/firmware/config.txt"
	    sudo sh -c 'echo "\ndtoverlay=i2c-gpio,bus=3,i2c_gpio_delay_us=1,i2c_gpio_sda=23,i2c_gpio_scl=24" >> /boot/firmware/config.txt'
	  fi
	
	  if [[ $(grep 'enable_uart=1' /boot/firmware/config.txt) ]]; then
	    echo "enable_uart=1 already in /boot/firmware/config.txt"
	  else
	    echo "adding enable_uart=1 to /boot/firmware/config.txt"
	    sudo sh -c 'echo "\nenable_uart=1" >> /boot/firmware/config.txt'
	  fi
	  
	  if [[ $(grep 'dtoverlay=disable-bt' /boot/firmware/config.txt) ]]; then
	    echo "dtoverlay=disable-bt already in /boot/firmware/config.txt"
	  else
	    echo "adding dtoverlay=disable-bt to /boot/firmware/config.txt"
	    sudo sh -c 'echo "\ndtoverlay=disable-bt" >> /boot/firmware/config.txt'
	  fi
	  
	  if [[ $(grep 'dtoverlay=dwc2' /boot/firmware/config.txt) ]]; then
	    echo "dtoverlay=dwc2 aalready in /boot/firmware/config.txt"
	  else
	    echo "adding dtoverlay=dwc2 to /boot/firmware/config.txt"
	    sudo sh -c 'echo "\ndtoverlay=dwc2" >> /boot/firmware/config.txt'
	  fi
	
	  if [[ $(grep 'modules-load=dwc2,g_ether' /boot/firmware/cmdline.txt) ]]; then
	    echo "modules-load=dwc2,g_ether already in /boot/firmware/cmdline.txt"
	  else
	    echo "adding modules-load=dwc2,g_ether to /boot/firmware/cmdline.txt"
	    sudo sed -i 's/ rootwait/ rootwait modules-load=dwc2,g_ether/g' /boot/firmware/cmdline.txt
	  fi
	  
	  if [[ $(grep 'dtparam=audio=on' /boot/firmware/config.txt) ]]; then
	    echo "dtparam=audio=on already in /boot/firmware/config.txt"
	  else
	    echo "adding dtparam=audio=on to /boot/firmware/config.txt"
	    sudo sh -c 'echo "\ndtparam=audio=on" >> /boot/firmware/config.txt'
	  fi
	
	  if [[ $(grep 'dtoverlay=audremap,enable_jack=on' /boot/firmware/config.txt) ]]; then
	    echo "dtoverlay=audremap,enable_jack=on already in /boot/firmware/config.txt"
	  else
	    echo "adding dtoverlay=audremap,enable_jack=on to /boot/firmware/config.txt"
	    sudo sh -c 'echo "\ndtoverlay=audremap,enable_jack=on" >> /boot/firmware/config.txt'
	  fi
	
	  if [[ $(grep 'dtoverlay=pwm,pin=18,func=2' /boot/firmware/config.txt) ]]; then
	    echo "dtoverlay=pwm,pin=18,func=2 already in /boot/firmware/config.txt"
	  else
	    echo "adding  to /boot/firmware/config.txt"
	    sudo sh -c 'echo "\ndtoverlay=pwm,pin=18,func=2" >> /boot/firmware/config.txt'
	  fi
	
	  if [[ $(grep 'disable_splash=1' /boot/firmware/config.txt) ]]; then
	    echo "disable_splash=1 already in /boot/firmware/config.txt"
	  else
	    echo "adding disable_splash=1 to /boot/firmware/config.txt"
	    sudo sh -c 'echo "\ndisable_splash=1" >> /boot/firmware/config.txt'
	  fi
	
	  if [[ $(grep 'boot_delay=0' /boot/firmware/config.txt) ]]; then
	    echo "boot_delay=0 already in /boot/firmware/config.txt"
	  else
	    echo "adding boot_delay=0 to /boot/firmware/config.txt"
	    sudo sh -c 'echo "\nboot_delay=0" >> /boot/firmware/config.txt'
	  fi
	
	  if [[ $(grep 'camera_auto_detect=1' /boot/firmware/config.txt) ]]; then
	    echo "camera_auto_detect=1 already in /boot/firmware/config.txt"
	  else
	    echo "adding camera_auto_detect=1 to /boot/firmware/config.txt"
	    sudo sh -c 'echo "\ncamera_auto_detect=1" >> /boot/firmware/config.txt'
	  fi
	
	  if ! grep -q force_turbo=1 /boot/firmware/config.txt ; then sudo sh -c 'echo "force_turbo=1" >> /boot/firmware/config.txt'; fi

	  sudo sh -c 'echo "\n" >> /boot/firmware/config.txt'

	  sudo sed -i 's/managed=false/managed=true/g' /etc/NetworkManager/NetworkManager.conf # allow nmcli to manage WiFi

	FILE=/boot/firmware/cmdline.txt
	if [[ $(grep "vc4.force_hotplug=1" $FILE) ]]; then
		echo "vc4.force_hotplug=1 already in $FILE"; 
	else
		echo "adding vc4.force_hotplug=1 to $FILE";
		sudo sed -i '1s/^/vc4.force_hotplug=1 /' $FILE
	fi

#	  if [ ! -d "/var/log/journal" ]; then # persistant journal logs across boots
		echo "Setting up journal logs across boots"
		sudo mkdir -p /var/log/journal &>/dev/null
		sudo systemd-tmpfiles --create --prefix /var/log/journal
		sudo systemctl restart systemd-journal-flush.service
		sudo sed -i 's/Storage=volatile/Storage=persistent/g' /etc/systemd/journald.conf
#	  fi

elif [[ $(grep 'trixie' /etc/os-release) ]]; then

	echo "Trixie detected, installation continuing."
	echo "Your Pi OS version is not Bookworm or Bullseye."
	echo "The software installation will likely not work."
	echo "See the README.md for how to install using Bookworm."
	echo

	echo "Are you sure you want to continue the installation (y/n)?"
	
	read -r ANS
	
	if [ "$ANS" = "n" ]; then	
	    exit 1
	fi
fi

/home/pi/CubeSatSim/config -V 2  # set maxcpus to 2

# FILE=/etc/modprobe.d/alsa-base.conf
# if [ -f "$FILE" ]; then
# 	echo "$FILE exists."
# 	if [[ $(grep "options snd-usb-audio index=2" $FILE) ]]; then
# 		echo "options snd-usb-audio index=2 already in $FILE"; 
# 	else
# 		echo "adding options snd-usb-audio index=2 to $FILE";
# 		sudo sed -i '$a options snd-usb-audio index=2' $FILE
# 		echo "options snd-usb-audio index=2" | sudo tee -a $FILE # > /dev/null
# 	fi
# else
# 	echo "creating $FILE"
# 	echo "options snd-usb-audio index=2" | sudo tee $FILE  # > /dev/null
# fi

FILE=/home/pi/CubeSatSim/sim.cfg
if [ -f "$FILE" ]; then
    echo "$FILE exists."

	changed=0
	value=`cat /home/pi/CubeSatSim/sim.cfg`
	# echo "$value"
	echo "$value" > /dev/null
	set -- $value
	
	if [ -z "$1" ] ; then n1="AMSAT" ; changed=1 ; else n1=$1 ; fi # callsign
	if [ -z "$2" ] ; then n2="0" ; changed=1 ; else n2=$2 ; fi # reset count
	if [ -z "$3" ] ; then n3="0" ; changed=1 ; else n3=$3 ; fi # lat
	if [ -z "$4" ] ; then n4="0" ; changed=1 ; else n4=$4 ; fi # lon
	if [ -z "$5" ] ; then n5="no" ; changed=1 ; else n5=$5 ; fi # sim mode
	if [ -z "$6" ] ; then n6="3" ; changed=1 ; else n6=$6 ; fi # squelch
	if [ -z "$7" ] ; then n7="434.9000" ; changed=1 ; else n7=$7 ; fi # transmit frequency
	if [ -z "$8" ] ; then n8="435.0000" ; changed=1 ; else n8=$8 ; fi # receive frequency
	if [ -z "$9" ] ; then n9="no" ; changed=1 ; else n9=$9 ; fi # hab mode
	if [ -z "${10}" ] ; then m1="0" ; changed=1 ; else m1=${10} ; fi # rx pl code 
	if [ -z "${11}" ] ; then m2="0" ; changed=1 ; else m2=${11} ; fi # tx pl code
	if [ -z "${12}" ] ; then m3="no" ; changed=1 ; else m3=${12} ; fi # random fail
	if [ -z "${13}" ] ; then m4="60" ; changed=1 ; else m4=${13} ; fi # random fail period
	if [ -z "${14}" ] ; then m5="no" ; changed=1 ; else m5=${14} ; fi # doppler mode

	if [ $changed -eq 1 ]; then
		echo -e "Current sim.cfg configuration file:"	
		echo
		echo $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11} ${12} ${13} ${14}
		echo -e "\nCubeSatSim configuration sim.cfg file updated to: \n"
		echo
		echo $n1 $n2 $n3 $n4 $n5 $n6 $n7 $n8 $n9 $m1 $m2 $m3 $m4 $m5
		echo $n1 $n2 $n3 $n4 $n5 $n6 $n7 $n8 $n9 $m1 $m2 $m3 $m4 $m5 > /home/pi/CubeSatSim/sim.cfg
		echo
	fi

else 
    echo "creating $FILE"
    echo "AMSAT 0 0 0 no 3 434.9 435 no 0 0 no 60 no" > /home/pi/CubeSatSim/sim.cfg
fi

if [[ $(grep 'cubesatsim' /etc/motd) ]]; then
	echo "motd already updated"
else
	echo "updating motd"
	sudo sh -c 'cat /home/pi/CubeSatSim/motd.txt >> /etc/motd'
fi

FILE=/home/pi/CubeSatSim/command_tx
if [ -f "$FILE" ]; then
    echo "$FILE exists."
else 
    echo "creating $FILE"
    echo "True\n" > /home/pi/CubeSatSim/command_tx
fi

FILE=/home/pi/CubeSatSim/command_count.txt
if [ -f "$FILE" ]; then
    echo "$FILE exists."
else 
    echo "creating $FILE"
    echo -n "0" > /home/pi/CubeSatSim/command_count.txt
fi
  
sudo apt-get  update && sudo apt-get dist-upgrade -y

# if [ $BULLSEYE -eq 1 ]; then
#	sudo apt-get purge -y python3-pip
#	sudo apt-get install -y python3-pip
# fi

cp /home/pi/CubeSatSim/groundstation/pacsat.desktop /home/pi/Desktop/pacsat.desktop
cp /home/pi/CubeSatSim/groundstation/gpredict.desktop /home/pi/Desktop/gpredict.desktop

if [ ! -d "/home/pi/venv" ]; then

	cd
	sudo apt-get install -y python3-venv
	sudo python3 -m venv venv
	source /home/pi/venv/bin/activate
	
	curl https://bootstrap.pypa.io/get-pip.py | sudo /home/pi/venv/bin/python3
	
	sudo /home/pi/venv/bin/pip3 install adafruit_extended_bus
	sudo /home/pi/venv/bin/pip3 install adafruit-circuitpython-ina219

fi

sudo apt-get remove pulseaudio -y

sudo apt-get install -y gcc g++ make cmake libasound2-dev libudev-dev libavahi-client-dev libgpiod-dev raspi-config 

# removed wiringpi and python-picamera python3-picamera 
sudo apt-get install -y git libasound2-dev i2c-tools build-essential libgd-dev libmagic-dev minicom

if [ -d "/home/pi/direwolf" ]; then

	cd
	cd direwolf
	# Get the URL of the 'origin' remote
	REPO_URL=$(git config --get remote.origin.url)
	
	# Check if the command was successful and a URL was retrieved
	if [ $? -eq 0 ] && [ -n "$REPO_URL" ]; then
	
		if [ ! "$REPO_URL" = "https://github.com/wb2osz/direwolf.git" ]; then
	
	    	echo "Current Direwolf git repository URL is $REPO_URL"
			sudo rm -r /home/pi/direwolf
		fi
	else
    	echo "Could not find the URL for the 'origin' remote for Direwolf"		
	fi
fi

if [ ! -d "/home/pi/direwolf" ]; then

	echo "Installing Direwolf from https://github.com/wb2osz/direwolf.git"
	cd	
	git clone https://github.com/wb2osz/direwolf.git
	cd direwolf
	mkdir build 
	cd build
	cmake ..
	make -j4
	sudo make install
	make install-conf

fi

	sudo apt-get install -y gpsd gpsd-clients libgps-dev python3-gps
	sudo systemctl disable gpsd
	sudo systemctl disable gpsd.socket

#if [ ! -d "/home/pi/WiringPi" ]; then
#	cd
#	git clone https://github.com/alanbjohnston/WiringPi
#	cd WiringPi
#	./build debian
#	sudo dpkg -i debian-template/wiringpi-2.61-1.deb
#fi

if [ ! -d "/home/pi/WiringPi3" ]; then
	cd
	git clone https://github.com/WiringPi/WiringPi.git WiringPi3
	cd WiringPi3
	./build debian
	mv debian-template/wiringpi*.deb .
	sudo apt-get install ./wiringpi*.deb
fi

cd

if [ ! $BULLSEYE -eq 1 ]; then
	sudo apt-get install -y libtiff6
fi

sudo apt-get install -y python3-pip python3-smbus libjpeg-dev zlib1g-dev libfreetype6-dev libopenjp2-7 python3-pil python3-serial libusb-1.0-0 libusb-1.0-0-dev

if [ $BULLSEYE -eq 1 ] || [ $UPDATE -eq 0 ] ; then

	sudo pip3 install --upgrade setuptools
	
	sudo pip3 install adafruit-blinka RPI.GPIO adafruit-extended-bus adafruit-circuitpython-ina219

fi

cd /home/pi/CubeSatSim

git pull --no-rebase > .updated

if [ $checkout -eq 1 ]; then
	git checkout $branch	
	git pull --no-rebase > .updated
	FLAG=1
	echo "Running update again"
	/home/pi/CubeSatSim/install
	exit
fi

grep 'install' /home/pi/CubeSatSim/.updated
if [[ $(grep 'install' /home/pi/CubeSatSim/.updated) ]]; then
	echo "install script updated, running again"
	/home/pi/CubeSatSim/install
	exit
fi

make debug

FILE=/home/pi/CubeSatSim/.mode
if [ -f "$FILE" ]; then
    echo "$FILE exists."
else 
    echo "creating $FILE"
    echo "b" > .mode
fi

if [ ! -d "/home/pi/g0kla_common" ]; then
	cd
	git clone https://github.com/alanbjohnston/g0kla_common.git
	cd g0kla_common/Debug/
	make clean
	make all
	sudo ./install.sh

else
	cd /home/pi/g0kla_common/Debug/
	
	git pull --no-rebase > .updated
	grep 'changed' /home/pi/g0kla_common/Debug/.updated
	if [[ $(grep 'changed' /home/pi/g0kla_common/Debug/.updated) ]]; then
	
		echo "updating g0kla_common"
		make clean
		make all
		FLAG=1
	fi
fi

FILE=/home/pi/pi_pacsat/Debug/pi_pacsat  # code has already been compiled
if [ ! -f "$FILE" ]; then

	cd
	git clone https://github.com/alanbjohnston/pi_pacsat.git
	#git clone https://github.com/ac2cz/pi_pacsat.git
	cd pi_pacsat
	#git checkout master-debug
	cd Debug
	make clean
	make all
	/home/pi/CubeSatSim/config -k -n
	
else
	cd /home/pi/pi_pacsat/Debug/
	
	git pull --no-rebase > .updated
	grep 'changed' /home/pi/pi_pacsat/Debug/.updated
	if [[ $(grep 'changed' /home/pi/pi_pacsat/Debug/.updated) ]]; then
	
		echo "updating pi_pacsat"
		make clean
		make all
		/home/pi/CubeSatSim/config -k -n
		FLAG=1
	fi
fi

FILE=/home/pi/pacsat_telem/Debug/pacsat_telem  # code has already been compiled
if [ ! -f "$FILE" ]; then
	cd
	sudo apt-get install -y libbsd-dev
	git clone https://github.com/alanbjohnston/pacsat_telem.git
	cd pacsat_telem
	git checkout master-fox
	cd Debug
	make clean
	make all
fi

cd /home/pi/pacsat_telem/Debug/

git pull --no-rebase > .updated
# git checkout master-fox
grep 'changed' /home/pi/pacsat_telem/Debug/.updated
if [[ $(grep 'changed' /home/pi/pacsat_telem/Debug/.updated) ]]; then

	echo "updating pacsat_telem"
	make clean
	make all
	FLAG=1
fi

sudo sed -i 's/#hdmi_group=1/hdmi_group=2/g' /boot/config.txt
sudo sed -i 's/#hdmi_mode=1/hdmi_mode=16/g' /boot/config.txt
sudo sed -i 's/#hdmi_force_hotplug=1/hdmi_force_hotplug=1/g' /boot/config.txt

sudo raspi-config nonint do_vnc 0



if [ ! -d "/home/pi/Desktop/PacsatGround" ]; then

	URL="https://www.g0kla.com/pacsat/downloads/test/"
	FILENAME=$(wget -q -O - $URL | grep -E -o -m 1 'PacsatGround_unix...........gz' | head -n 1)
	echo "Downloading latest PacsatGround Station version" $FILENAME
	wget $URL/$FILENAME -O PacsatGround_unix.tar.gz
	tar -xzf PacsatGround_unix.tar.gz -C /home/pi/Desktop

fi

sudo usermod -a -G gpio pi
sudo apt-get install default-jdk -y

FILE=/home/pi/Desktop/PacsatGround/spacecraft/PacSatSim.commands
if [ ! -f "$FILE" ]; then
	echo "copying missing commands file to spacecraft"
	cp /home/pi/CubeSatSim/spacecraft/PacSatGround_0.46o/PacSatSim.commands $FILE
fi

FILE=/home/pi/Desktop/PacsatGround/PacSatSim.commands
if [ ! -f "$FILE" ]; then
	echo "copying missing commands file"
	cp /home/pi/CubeSatSim/spacecraft/PacSatGround_0.46o/PacSatSim.commands $FILE
fi

cd

if [ ! -d "/home/pi/PiSSTVpp" ]; then

  sudo apt-get update -y
  sudo apt-get install -y python-picamera python3-picamera build-essential libgd-dev libmagic-dev
  cd
  git clone https://github.com/alanbjohnston/PiSSTVpp.git
  cd PiSSTVpp
  make pisstvpp

fi

if [ ! -d "/home/pi/rpitx" ]; then

	sudo apt-get install -y libraspberrypi-dev
	cd
	git clone https://github.com/alanbjohnston/rpitx.git
	cd rpitx
	./install.sh
	cd
else

	if [[ $(grep 'SYNCWITHPWM'  /home/pi/rpitx/src/librpitx/src/fskburst.h) ]]; then
	    echo "rpitx library already updated"
	else
	    echo "updating rpitx"
	    cd  /home/pi/rpitx
	    git pull
	    ./update.sh
	    cd
	fi
fi

FILE=/etc/systemd/system/cubesatsim.service
if [ -f "$FILE" ]; then
	if [[ $(diff /home/pi/CubeSatSim/systemd/cubesatsim.service /etc/systemd/system/cubesatsim.service) ]]; then
	  echo "changed cubesatsim.service."
	  sudo cp /home/pi/CubeSatSim/systemd/cubesatsim.service /etc/systemd/system/cubesatsim.service
	  FLAG=1
	else
	  echo "no changes to cubesatsim.service."
	fi
else
  echo "creating cubesatsim.service."
  sudo cp /home/pi/CubeSatSim/systemd/cubesatsim.service /etc/systemd/system/cubesatsim.service
  sudo systemctl enable cubesatsim

  FLAG=1
fi

FILE=/etc/systemd/system/rpitx.service
if [ -f "$FILE" ]; then
  sudo systemctl disable rpitx
  sudo rm /etc/systemd/system/rpitx.service
fi

if [[ -z $(sudo systemctl is-active packagekit | grep inactive) ]]; then 
  echo "Removing packagekit so won't auto check for updates on boot"
  sudo systemctl stop packagekit
  sudo systemctl disable packagekit
  sudo apt-get remove -y packagekit
fi

FILE=/etc/systemd/system/transmit.service
if [ -f "$FILE" ]; then
  if [[ $(diff /home/pi/CubeSatSim/systemd/transmit.service /etc/systemd/system/transmit.service) ]]; then
    echo "changed transmit.service."
    sudo cp /home/pi/CubeSatSim/systemd/transmit.service /etc/systemd/system/transmit.service
    FLAG=1
  else
    echo "no change to transmit.service."
  fi
else
  echo "creating transmit.service."
  sudo cp /home/pi/CubeSatSim/systemd/transmit.service /etc/systemd/system/transmit.service
  FLAG=1
fi

FILE=/etc/systemd/system/command.service
if [ -f "$FILE" ]; then
  if [[ $(diff /home/pi/CubeSatSim/systemd/command.service /etc/systemd/system/command.service) ]]; then
    echo "changed command.service."
    sudo cp /home/pi/CubeSatSim/systemd/command.service /etc/systemd/system/command.service
    FLAG=1
  else
    echo "no change to command.service."
  fi
else
  echo "creating command.service."
  sudo cp /home/pi/CubeSatSim/systemd/command.service /etc/systemd/system/command.service
  sudo systemctl enable command
  FLAG=1
fi

FILE=/etc/systemd/system/pacsatsim.service
if [ -f "$FILE" ]; then
  if [[ $(diff /home/pi/CubeSatSim/systemd/pacsatsim.service /etc/systemd/system/pacsatsim.service) ]]; then
    echo "changed pacsatsim.service."
    sudo cp /home/pi/CubeSatSim/systemd/pacsatsim.service /etc/systemd/system/pacsatsim.service
    FLAG=1
  else
    echo "no change to pacsatsim.service."
  fi
else
  echo "creating pacsatsim.service."
  sudo cp /home/pi/CubeSatSim/systemd/pacsatsim.service /etc/systemd/system/pacsatsim.service
  FLAG=1
fi

FILE=/etc/systemd/system/frequency.service
if [ -f "$FILE" ]; then
  if [[ $(diff /home/pi/CubeSatSim/systemd/frequency.service /etc/systemd/system/frequency.service) ]]; then
    echo "changed frequency.service."
    sudo cp /home/pi/CubeSatSim/systemd/frequency.service /etc/systemd/system/frequency.service
    FLAG=1
  else
    echo "no change to frequency.service."
  fi
else
  echo "creating frequency.service."
  sudo cp /home/pi/CubeSatSim/systemd/frequency.service /etc/systemd/system/frequency.service
  FLAG=1
fi

FILE=/etc/init.d/listen-for-shutdown.sh
if [ -f $FILE ]; then
	echo "Uninstalling pi-power-button"
    sudo rm $FILE
fi

FILE=/etc/systemd/system/pushbutton.service
if [ -f "$FILE" ]; then
  if [[ $(diff /home/pi/CubeSatSim/systemd/pushbutton.service /etc/systemd/system/pushbutton.service) ]]; then
    echo "changed pushbutton.service."
    sudo cp /home/pi/CubeSatSim/systemd/pushbutton.service /etc/systemd/system/pushbutton.service
	sudo systemctl enable pushbutton
    FLAG=1
  else
    echo "no change to pushbutton.service."
  fi
else
  echo "creating pushbutton.service."
  sudo cp /home/pi/CubeSatSim/systemd/pushbutton.service /etc/systemd/system/pushbutton.service
  sudo systemctl enable pushbutton
  FLAG=1
fi

FILE=/etc/OliveTin/config.yaml
if [ -f "$FILE" ]; then
  if [[ $(diff /home/pi/CubeSatSim/OliveTin/config.yaml /etc/OliveTin/config.yaml) ]]; then
    echo "changed config.yaml"
    sudo cp /home/pi/CubeSatSim/OliveTin/config.yaml /etc/OliveTin/config.yaml
	sudo systemctl daemon-reload
	sudo systemctl restart OliveTin
  else
    echo "no change to config.yaml"
  fi
else
  echo "creating config.yaml"
  cd /tmp
  wget https://github.com/OliveTin/OliveTin/releases/download/3000.18.1/OliveTin_linux_armv7.deb
  sudo dpkg -i OliveTin_linux_armv7.deb
  sudo cp /home/pi/CubeSatSim/OliveTin/config.yaml /etc/OliveTin/config.yaml
  sudo systemctl enable --now OliveTin
fi

FILE=/etc/systemd/system/OliveTin.service
if [ -f "$FILE" ]; then
  if [[ $(diff /home/pi/CubeSatSim/systemd/OliveTin.service /etc/systemd/system/OliveTin.service) ]]; then
    echo "changed OliveTin.service."
    sudo cp /home/pi/CubeSatSim/systemd/OliveTin.service /etc/systemd/system/OliveTin.service
	sudo systemctl daemon-reload
	sudo systemctl restart OliveTin
    FLAG=1
  else
    echo "no change to OliveTin.service."
  fi
else
  echo "creating OliveTin.service."
  sudo cp /home/pi/CubeSatSim/systemd/OliveTin.service /etc/systemd/system/OliveTin.service
  sudo systemctl daemon-reload
  sudo systemctl enable OliveTin
  FLAG=1
fi

FILE=/etc/asound.conf
if [ -f "$FILE" ]; then
  if [[ $(diff /home/pi/CubeSatSim/asound.conf /etc/asound.conf) ]]; then
    echo "changed /etc/asound.conf."
    sudo cp /home/pi/CubeSatSim/asound.conf /etc/asound.conf
    FLAG=1
  else
    echo "no change to /etc/asound.conf."
  fi
else
  echo "creating /etc/asound.conf."
  sudo cp /home/pi/CubeSatSim/asound.conf /etc/asound.conf
  FLAG=1
fi

sudo alsactl init 
sleep 5
echo "Turn Command and Control on and off to activate MicVolume"
touch /home/pi/CubeSatSim/command_control
sudo systemctl start command
sleep 10
sudo rm /home/pi/CubeSatSim/command_control
sudo systemctl restart command
sudo alsactl init 
sleep 5
/home/pi/CubeSatSim/config -L 75

FILE=/home/pi/CubeSatSim/sstv_image_1_320_x_256.jpg
if [ ! -f "$FILE" ]; then
    echo "Copying SSTV image 1."
    cp /home/pi/CubeSatSim/sstv/sstv_image_1_320_x_256.jpg /home/pi/CubeSatSim/sstv_image_1_320_x_256.jpg
fi
    
FILE=/home/pi/CubeSatSim/sstv_image_2_320_x_256.jpg
if [ ! -f "$FILE" ]; then
    echo "Copying SSTV image 2."
    cp /home/pi/CubeSatSim/sstv/sstv_image_2_320_x_256.jpg /home/pi/CubeSatSim/sstv_image_2_320_x_256.jpg
fi

sudo sed -i 's/DEVICES=""/DEVICES="\/dev\/serial0"/g' /etc/default/gpsd

sudo sed -i 's/GPSD_OPTIONS=""/GPSD_OPTIONS="-s 9600"/g' /etc/default/gpsd

if [ ! -d "/home/pi/fctelem" ]; then
	echo "Installing fctelem binary v0.2 for FUNcube mode"
	cd
	mkdir /home/pi/fctelem
	mkdir /home/pi/fctelem/public_html
	cd fctelem
	wget https://github.com/alanbjohnston/go/releases/download/v0.2/fctelem.zip
	unzip -u fctelem.zip
	FLAG=1
elif [ ! -f "/home/pi/fctelem/v0.2" ]; then
	echo "Updating fctelem binary to version v0.2 for FUNcube mode"
	cd
	cd /home/pi/fctelem
	sudo mv fctelem fctelem.bk
	sudo mv fcdecode.conf fcdecode.conf.bk
	sudo mv fctelem.zip fctelem.zip.1
	wget https://github.com/alanbjohnston/go/releases/download/v0.2/fctelem.zip
	unzip -u fctelem.zip
	FLAG=1
fi

if [ ! -f "/home/pi/MPU6050-C-CPP-Library-for-Raspberry-Pi/mpu6050" ]; then
	echo "Installing MPU6050-C-CPP-Library-for-Raspberry-Pi"
	sudo apt-get install -y libi2c-dev
	cd
	git clone https://github.com/alanbjohnston/MPU6050-C-CPP-Library-for-Raspberry-Pi.git
	cd MPU6050-C-CPP-Library-for-Raspberry-Pi
	sudo make install
	make payload
fi

cd /home/pi/MPU6050-C-CPP-Library-for-Raspberry-Pi
git checkout master
git pull --no-rebase > .updated_p

if [[ $(grep 'changed' /home/pi/MPU6050-C-CPP-Library-for-Raspberry-Pi/.updated_p) ]]; then
	echo "updating MPU6050-C-CPP-Library-for-Raspberry-Pi"
	sudo make install
	make payload
else
	echo "nothing to do for MPU6050-C-CPP-Library-for-Raspberry-Pi."
fi 

if [ ! -f "/home/pi/raspberry-pi-bme280/bme280" ]; then
	echo "Installing raspberry-pi-bme280"
	sudo apt-get install -y libi2c-dev
	cd
	git clone https://github.com/alanbjohnston/raspberry-pi-bme280.git
	cd raspberry-pi-bme280
	git checkout payload
	make 
fi

cd /home/pi/raspberry-pi-bme280
git checkout payload
git pull --no-rebase > .updated_p

if [[ $(grep 'changed' /home/pi/raspberry-pi-bme280/.updated_p) ]]; then

	echo "updating raspberry-pi-bme280"
	make

else
	echo "nothing to do for raspberry-pi-bme280."
fi 

if [ ! -f "/home/pi/fcdctl/fcdctl" ]; then
	echo "Installing fcdctl to set FUNcubeDongle Pro gain"
	sudo rm /var/lib/dpkg/info/python3-pip.list
	sudo apt-get install python3-pip --reinstall
	sudo apt-get install -y python3-smbus libusb-1.0 
	cd
	git clone https://github.com/csete/fcdctl.git
	cd fcdctl
	make fcdpp
fi

if [ ! -f "/home/pi/ssdv/ssdv" ]; then
	cd
	echo "Installing SSDV for FUNcube mode"
	git clone https://github.com/alanbjohnston/ssdv.git  # install ssdv for FUNcube images
	cd ssdv
	make
fi

if [ ! -f "/home/pi/FT857d/examples/FT857d/ft857d" ]; then
	cd
	echo "Installing FT857d for Doppler rigctld control mode"
	git clone https://github.com/alanbjohnston/FT857d.git
	cd FT857d
	git checkout pi	
	cd examples/FT857d	
	g++ main.c ../../src/ft857d.cpp -lwiringPi -o ft857d

	sudo apt-get install -y libhamlib-utils socat gpredict
fi

cd /home/pi/FT857d
git checkout pi
git pull --no-rebase > .updated_p

if [[ $(grep 'changed' //home/pi/FT857d/.updated_p) ]]; then
	echo "updating FT857d"
	cd examples/FT857d	
	g++ main.c ../../src/ft857d.cpp -lwiringPi -o ft857d
else
	echo "nothing to do for FT857d."
fi 

cd

#echo "Would you like to reboot to complete the installation (y/n)?"

#read -r ANS

#if [ "$ANS" = "y" ]; then

#    sudo reboot now

#else

 #   echo "The CubeSatSim software will start next time you reboot"
    
#fi

sed -i 's/quick_exec=0/quick_exec=1/' ~/.config/libfm/libfm.conf

if [ ! -d "/home/pi/Icons" ]; then
	cd
	mkdir Icons
	cd Icons
	#wget http://cubesatsim.org/icons/*
	#wget -r -nd --no-parent -A 'bar.*.tar.gz' http://url/dir/
	wget -r -nd --no-parent -A '*' https://cubesatsim.org/icons/
fi

sudo apt-get install -y raspberrypi-ui-mods rpi-connect ttyd

sudo apt-get autoremove -y

if [[ $(gpio -v | grep "Pi 4") ]] && [[ ! $(sudo raspi-config nonint get_browser | grep "chromium") ]] ; then
	echo "Since Pi 4, changing default browser to Chromium"
	sudo raspi-config nonint do_browser chromium
fi

if [[ $(gpio -v | grep "Pi 5") ]] && [[ ! $(sudo raspi-config nonint get_browser | grep "firefox") ]] ; then
	echo "Since Pi 5, changing default browser to Firefox"
	sudo raspi-config nonint do_browser firefox
fi


if [ "$NETWORK" = "0" ]  ; then
	echo "Enabling NetworkManager.  You will need to login again and restart to complete the install/update."
	sudo sed -i 's/managed=false/managed=true/g' /etc/NetworkManager/NetworkManager.conf # allow nmcli to manage WiFi
	sudo systemctl enable --now NetworkManager && sudo nmcli networking on && sleep 5 && sudo nmcli dev wifi connect "$ssid" password "$password"
fi

if [ "$noreboot" = "0" ] ; then  

	if [ $FLAG -eq 1 ]; then # Not sure if this is needed
	  echo "systemctl daemon-reload and reboot"
	  sudo systemctl daemon-reload 
	  sudo reboot -h now
#  sudo  cubesatsim
	else
	  grep 'changed' /home/pi/CubeSatSim/.updated
	  if [[ $(grep 'changed' /home/pi/CubeSatSim/.updated) ]]; then
	    echo "reboot due to code changes " | wall
	    sudo reboot -h now
#    sudo  cubesatsim
	  else
	    echo "nothing to do."
	  fi  
	fi
else
	if [ $FLAG -eq 1 ]; then
		echo "reboot needed for changes to take effect" | wall
	fi
fi

echo
echo "You should restart to complete this operation with command:"
echo "sudo reboot now"
echo
