#!/bin/bash
# Environmental variable
CURUSER=$(whoami)
OSUSED=$(lsb_release -si)
UBUNTU=$(grep -i "PRETTY_NAME" /etc/os-release | cut -d "=" -f 2 | sed 's/\"//g')
ArcElf=$(uname -m)

NC='\033[0m'			  # Reset	
Red='\033[0;31m'          # Red
Green='\033[0;32m'        # Green
Yellow='\033[0;33m'       # Yellow
Cyan='\033[0;36m'         # Cyan

clear

# Uninstall -------------------------------------------------------
if [ "$1" == "uninstall" ]; then

	echo -e "${Green}Solstus Solar IoT Uninstaller Script${NC}"
	echo -e
	echo -e "${Yellow}Welcome $CURUSER"
	echo -e
	echo -e "This script will now uninstall Solstus Solar IoT on this PC${NC}\n"
	echo -e "${Red}WARNING: ALL SOLSTUS DATA AND CONFIGURATIONS WILL BE LOST${NC}\n"
	printf  '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' -
	echo -e ${Cyan}
	read -p "Are you sure you want to continue ? [y/n]: " confirmOp
	echo -e ${NC}

	if [[ "$confirmOp" != "y" ]]; then
		echo -e "\n${Yellow}User Aborted${NC}\n"
		exit 0
	fi

	# Remove Systemd
	if [ -f /etc/systemd/system/solstus.service ]; then		
		echo -e "\n*** ${Red}Removing Solstus Systemd Service${NC}\n"		
		sudo systemctl stop solstus
		sudo systemctl disable solstus
		sudo rm /etc/systemd/system/solstus.service
		sudo systemctl daemon-reload
		sudo systemctl reset-failed
	fi
	
	echo -e "\n*** ${Red}Stopping Apache Web server\n${NC}"
	sudo systemctl stop apache2	

	echo -e "\n*** ${Red}Killing any and all Solstus Instances\n${NC}"
	ps -ef | grep 'startsolstus.sh' | grep -v grep | awk '{print $2}'| xargs kill -9 2> /dev/null && \
	if pgrep Solstus; then pkill Solstus; fi
	
	cd /home/$CURUSER
	
	if [ -f /home/$CURUSER/Solstus ]; then	
		echo -e "\n*** ${Red}Removing Solstus application\n${NC}"
		rm /home/$CURUSER/Solstus	
	fi
	
	if [ -f /home/$CURUSER/Solstus.conf ]; then	
		echo -e "\n*** ${Red}Removing Solstus configuration file\n${NC}"
		rm /home/$CURUSER/Solstus.conf	
	fi
	
	if [ -f /home/$CURUSER/updatesolstus.sh ]; then
		echo -e "\n*** ${Red}Removing Solstus update Script\n${NC}"
		rm /home/$CURUSER/updatesolstus.sh
	fi
	
	if [ -f /home/$CURUSER/startsolstus.sh ]; then
		echo -e "\n*** ${Red}Removing Solstus startup Script\n${NC}"
		rm /home/$CURUSER/startsolstus.sh
	fi
	
	if [ -f /home/$CURUSER/solstus-source.zip ]; then
		echo -e "\n*** ${Red}Removing Solstus sources zip file\n${NC}"
		rm /home/$CURUSER/solstus-source.zip
	fi
	
	if [ -f /home/$CURUSER/diagnostics.txt ]; then
		echo -e "\n*** ${Red}Removing Solstus diagnostic log file\n${NC}"
		rm /home/$CURUSER/diagnostics.txt	
	fi
	
	if [ -d /home/$CURUSER/html ]; then
		echo -e "\n*** ${Red}Removing Solstus front-end directory and files\n${NC}"
		rm -r /home/$CURUSER/html
	fi
	
	if [ -d /home/$CURUSER/qtmqtt ]; then
		echo -e "\n*** ${Red}Removing Solstus MQTT directory and files\n${NC}"
		rm -r /home/$CURUSER/qtmqtt
	fi
		
	# Undo Udev Rules
	if [ -f /etc/udev/rules.d/69-inverter.rules ]; then
		echo -e "\n*** ${Red}Remove custom udev rules\n${NC}"
		sudo rm /etc/udev/rules.d/69-inverter.rules
	fi
	
	# Reset apache	
	if [[ -L /var/www/html ]]; then
		echo -e "\n*** ${Red}Reset Apache web server directory\n${NC}"	
		sudo rm /var/www/html
		sudo mkdir /var/www/html
		sudo chown -R $CURUSER:www-data /var/www/html
		sudo chmod -R 770 /var/www/html
		sudo chown $CURUSER:www-data /var/www/html
	fi
		
	# SQL Database
	echo -e ${Cyan}
	read -p "Delete Solstus Database and all its information ? [y/n]: " confirma
	echo -e ${NC}	
	if [[ "$confirma" == "y" ]]; then
		echo -e "\n*** ${Red}Deleting Solstus database and data\n${NC}"
		sudo mysql -uadmin -padmin -e "DROP DATABASE Solstus"
	fi
	
	# Sudo File Restore
	if [ -f /etc/sudoers.backup.solstus ]; then
		echo -e "\n*** ${Green}Restored Sudoers file to original state\n${NC}"
		sudo mv /etc/sudoers.backup.solstus /etc/sudoers
	else
		echo -e "\n*** ${Red}Backup sudo file missing,\n${NC}You will need to manually remove the entries by editing ${Yellow}/etc/sudoers${NC}"
	fi
	
	# Reset php upload file sizes
	echo -e "\n*** ${Green}Reset PHP Upload File sizes ... ${NC} \n"
	PHPFILEPATH=`php -i | grep /.+/php.ini -oE`
	sudo cp $PHPFILEPATH.bak $PHPFILEPATH
	
	echo -e "\n*** ${Green}Restarting Apache Web Server\n${NC}"
	sudo systemctl start apache2
		
	echo -e ${Red}
	echo -e "*** Do you want to Remove all Dependencies that was installed ? ***"
	echo -e "It's recommended to leave these, they won't cause issues BUT..."
	echo -e "Other software might also use them, if you remove them you might break other stuff"
	
	echo -e ${Cyan}
	read -p "Remove Dependencies that was installed! ARE YOU SURE ? [y/N]: " confirmb
	echo -e ${NC}
	
	if [[ "$confirmb" == "y" ]]; then
		# Remove packages
		echo -e "\n*** ${Red} Removing dependencies for Solstus using Ubuntu repositories ${NC} \n"
		sudo apt remove qtbase5-dev qtchooser qt5-qmake qtbase5-dev-tools qt5-qmake-bin build-essential git htop curl mosquitto mosquitto-clients libqt5core5a libqt5dbus5 libqt5sql5-mysql \
		libqt5network5 libqt5serialport5 apache2 php php-mysql libapache2-mod-php php-mbstring php-common php-gd \
		php-curl php-cli mariadb-server mariadb-client mariadb-common mysql-common mcrypt \
		mariadb-client mariadb-common mysql-common libmariadb-dev-compat libqt5sql5-mysql libqt5sql5 libqt5sql5-sqlite \
		libqt5serialbus5-dev libqt5serialport5-dev libqt5networkauth5-dev libqt5networkauth5 libqt5concurrent5 libmariadb-dev \
		zerotier-one phpmyadmin anydesk openssh-server;
		
		if [ -f /etc/apt/sources.list.d/anydesk.list ]; then		
			echo -e "\n*** ${Red}Remove source list\n${NC}"
			sudo rm /etc/apt/sources.list.d/anydesk.list
		fi		
		sudo apt update
		echo -e "\n*** ${Red}Cleaning up...\n${NC}"
		sudo apt autoremove -y
	fi
	
	echo -e "${Green}Solstus was Uninstalled - It's as if we were never here...${NC}\n"	
	exit 0
fi

# Install ---------------------------------------------------------
echo -e "${Green}Solstus Solar IoT Installer Script${NC}"
echo -e
echo -e "${Cyan}Supported Linux Operating Systems:${NC}"
echo -e "x64 Ubuntu 22.04+ LTS Jammy Jellyfish"
echo -e "x64 Linux Mint 21.2+"
echo -e "x32 Debian RaspOS Buster/bullseye (For Raspberry Pi)"
echo -e
echo -e "${Red}Please Note:${NC}"
echo -e "A 64Bit OS is required for this installation. Unless its on the Raspberry Pi"
echo -e
echo -e "${Yellow}To uninstall Solstus:${NC}"
echo -e	"Start this script with the ${Red}uninstall${Yellow} argument${NC}"
echo -e "E.g ./solstus_installer_Linux_x64.sh ${Red}uninstall${NC}"
echo -e
echo -e "${Green}Created by: Anton Silvers @ Micro Fusion Computers${NC}"
echo -e "${Green}Version 0.6 Build: 03 Sep 2024${NC}"
echo -e
printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' -

if [[ "$CURUSER" == "root" ]]; then
	echo -e "\n${Red}Cannot run this script as root or with sudo directly, restart the installation script as a normal user${NC}\n"
	exit 1
fi

echo -e "${Yellow}Welcome $CURUSER"
echo -e
echo -e "This script will install Solstus Solar IoT on this PC\n"
echo -e "Please make sure this is a clean install before you start.\n"
echo -e "This script will modify core aspects of the system and expects that the OS installed"
echo -e "is not already assigned to a spesific role such as a webserver or MySQL server etc${NC}\n"

echo -e ${Cyan}
read -p "Are you sure you want to continue ? [y/n]: " confirm
echo -e ${NC}

if [[ "$confirm" != "y" ]]; then
	echo -e "\n${Yellow}User Aborted${NC}\n"
	exit 0
fi

if [[ "$OSUSED" == "Ubuntu" || "$OSUSED" == *"Ubuntu"* || "$UBUNTU" == *"Ubuntu"* || "$OSUSED" == "Linuxmint" ]]; then

	# Update repo's 
	echo -e "\n*** ${Green} Making sure all apt packages are up to date... ${NC} \n"
	sudo apt update && sudo apt-get upgrade

	# Install Apache Web Server and Development Environment packages for Ubuntu
	echo -e "\n*** ${Green} Installing dependencies for Solstus using Ubuntu repositories ${NC} \n"
	(sudo apt install qtbase5-dev qtchooser qt5-qmake qtbase5-dev-tools qt5-qmake-bin build-essential git htop curl mosquitto mosquitto-clients libqt5core5a libqt5dbus5 libqt5sql5-mysql \
	libqt5network5 libqt5serialport5 apache2 php php-mysql libapache2-mod-php php-mbstring php-common php-gd \
	php-curl php-cli mariadb-server mariadb-client mariadb-common mysql-common mcrypt \
	mariadb-client mariadb-common mysql-common libmariadb-dev-compat libqt5sql5-mysql libqt5sql5 libqt5sql5-sqlite \
	libqt5serialbus5-dev libqt5serialport5-dev libqt5networkauth5-dev libqt5networkauth5 libqt5concurrent5 \
	libmariadb-dev -y ) || ( echo "Some Dependencies Was Not Found" && exit 32 )

elif [[ "$OSUSED" == "Debian" || "$OSUSED" == "Raspbian" ]]; then	

	# Update repo's 
	echo -e "\n*** ${Green} Making sure all apt packages are up to date... ${NC} \n"
	sudo apt update && sudo apt-get upgrade

	# Install Apache Web Server and Development Environment packages for Debian Raspberry Pi OS
	echo -e "\n*** ${Green} Installing dependencies for Solstus using Debian repositories ${NC}\n"
	(sudo apt install qtbase5-dev qtchooser qt5-qmake qtbase5-dev-tools qt5-qmake-bin build-essential git htop curl mosquitto mosquitto-clients libqt5core5a libqt5dbus5 libqt5sql5-mysql \
	libqt5network5 libqt5serialport5 apache2 php php-mysql libapache2-mod-php php-mbstring php-common php-gd \
	php-curl php-cli mariadb-server mariadb-client mariadb-common mysql-common mcrypt \
	mariadb-client mariadb-common mysql-common libmariadb-dev-compat libqt5sql5-mysql libqt5sql5 libqt5sql5-sqlite \
	libqt5serialbus5-dev libqt5serialport5-dev libqt5networkauth5-dev libqt5networkauth5 libqt5concurrent5 \
	libmariadb-dev -y ) || ( echo "Some Dependencies Was Not Found" && exit 32 )

else
	echo -e "\n*** ${Red} Unsuppored Linux Distro, Only Debian 10/11 (RaspOS), Linux Mint 21+ and Ubuntu 22.04+ LTS is currently supported.${NC}\n"
	exit 2
fi

echo -e "\n*** ${Green} Installing Solstus for user $CURUSER ${NC}"

if [ ! -d /home/$CURUSER/html ]; then	
	# Prepare Web Front-end Directory linking /var/www/html to home dir
	printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' -
	echo -e "\n*** ${Green} Preparing Web directory for Solstus... ${NC}\n"
	mkdir /home/$CURUSER/html
	sudo rm -r /var/www/html/*
	sudo rm -r /var/www/html
	sudo ln -s /home/$CURUSER/html/ /var/www
	sudo chown -R $CURUSER:www-data /home/$CURUSER/html
	sudo chmod -R 770 /home/$CURUSER/html
	sudo chown $CURUSER:www-data /home/$CURUSER	
	
	if [[ "$OSUSED" == "Debian" || "$OSUSED" == "Raspbian" ]]; then	
		sudo chmod -R +x /home/$CURUSER/	
	fi	
	echo -e "\n*** ${Green} Preparing Web directory Done ${NC} \n"
fi

# Install Anydesk and SSH
echo -e ${Cyan}
read -p "Do you want to install remote access using SSH ? [y/n]: " dconfirma
echo -e ${NC}

if [[ "$dconfirma" == "y" ]]; then
	
	sudo apt install openssh-server -y
	echo -e "\n*** ${Green} Installed remote access SSH Done ${NC}\n"
fi

# install PHPMyAdmin
printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' -
echo -e "\n*** ${Green} Installing PHPMyAdmin... ${NC}\n"
echo -e ${Yellow}
read -p "*** NOTE: Make sure to select APACHE when asked [Press Enter To Continue]" null
echo -e ${NC}

sudo apt install phpmyadmin -y

# SQL Password
echo -e "\n${Cyan}"
read -p "Please enter your MySQL [Password] again that you just created: " name
psw=${name:-Password}
echo -e ${NC}

# SQL Base Config
echo -e "\n*** ${Green} Creating Solstus database... ${NC}"
printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' -
sudo mysql -e "CREATE DATABASE IF NOT EXISTS Solstus" 

echo -e "\n*** ${Green} Creating User for MySQL admin account... ${NC}"
sudo mysql -uroot -p$psw -e "CREATE USER 'admin'@'localhost' IDENTIFIED BY 'admin'; GRANT ALL PRIVILEGES ON *.* TO 'admin'@'localhost' WITH GRANT OPTION; FLUSH PRIVILEGES;"

echo -e "\n*** ${Green} Setting User for MySQL Solstus database... ${NC}"
sudo mysql -uroot -p$psw -e "CREATE USER 'solstus'@'localhost' IDENTIFIED BY 'raspberry'; GRANT ALL PRIVILEGES ON Solstus.* TO 'solstus'@'localhost'; FLUSH PRIVILEGES;"

echo -e "\n*** ${Green} Creating tables in Solstus database... ${NC}"
sudo mysql -uroot -p$psw -e "use Solstus; CREATE TABLE IF NOT EXISTS InvMODE (_id INT AUTO_INCREMENT PRIMARY KEY, _currentMode VARCHAR(2), _TimeStamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP) ENGINE=INNODB;"
sudo mysql -uroot -p$psw -e "use Solstus; CREATE TABLE IF NOT EXISTS InvSettings (_id INT AUTO_INCREMENT PRIMARY KEY, _InverterPriority_POP TINYTEXT, _InvBatteryCutOffVoltage TINYTEXT, _InvBatteryBulkVoltage TINYTEXT, _InvBatteryFloatVoltage TINYTEXT) ENGINE=INNODB;"
sudo mysql -uroot -p$psw -e "use Solstus; CREATE TABLE IF NOT EXISTS InvStatus (_id INT AUTO_INCREMENT PRIMARY KEY, _SBUpriority SMALLINT(6), _ConfigChanged SMALLINT(6), _SSCFirwareChanged SMALLINT(6), _LoadStatus SMALLINT(6), _BatVoltToSteadyWhileCharging SMALLINT(6), _ChargingStatus SMALLINT(6), _FloatMode SMALLINT(6), _SwitchedOn SMALLINT(6), _Reserved SMALLINT(6), _TimeStamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP) ENGINE=INNODB;" 
sudo mysql -uroot -p$psw -e "use Solstus; CREATE TABLE IF NOT EXISTS PVCode (_id INT(10) AUTO_INCREMENT PRIMARY KEY, _code TEXT, _des TEXT, _TimeStamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP) ENGINE=INNODB;" 
sudo mysql -uroot -p$psw -e "use Solstus; CREATE TABLE IF NOT EXISTS PVData (_id BIGINT(20) AUTO_INCREMENT PRIMARY KEY, _GridInputVolts TINYTEXT, _GridInputHz TINYTEXT, _GridWatts TINYTEXT, _SolarFeedGridWatts TINYTEXT, _InvOutputVolts TINYTEXT, _InvOutupHz TINYTEXT, _LoadVA TINYTEXT, _OutputWatts TINYTEXT, _InvOutPutLoadPercentage TINYTEXT, _BusVoltage TINYTEXT, _BatteryVoltage TINYTEXT, _BatteryChargeAmps TINYTEXT, _BatteryCapacity TINYTEXT, _InvTemp TINYTEXT,	_PVInputCurrentAmps TINYTEXT, _PVInputVolts TINYTEXT, _BatteryVoltageSSC TINYTEXT, _BatteryDischargeCurrentAmps TINYTEXT, _DeviceStatus1 TINYTEXT, _BatteryVoltOffsetFanMVolts TINYTEXT, _EEPROMVersion TINYTEXT, _PVChargePower TINYTEXT, _DeviceStatus2 TINYTEXT,	_BatteryTemp TINYTEXT, _TimeStamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP) ENGINE=INNODB;"
sudo mysql -uroot -p$psw -e "use Solstus; CREATE TABLE IF NOT EXISTS User (_id INT(11) AUTO_INCREMENT PRIMARY KEY, _FirstName TEXT, _LastName TEXT, _PassWord TEXT, _Serial TEXT, _Activation TEXT, _TimeStamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP) ENGINE=INNODB;"

# Patch to Fix Slow Downs Over Time In MySQL
escaped_psw=$(echo "$psw" | sed 's/\\/\\\\/g; s/\$/\\$/g')
index_exists=$(sudo mysql -uroot -p"$escaped_psw" -N -e "USE Solstus; SHOW INDEX FROM PVData WHERE Key_name = 'idx_pvdata_timestamp';")
if [[ -z "$index_exists" ]]; then
  echo -e "\n*** ${Yellow} Index 'idx_pvdata_timestamp' not found. Creating... ${NC} \n"
  sudo mysql -uroot -p"$escaped_psw" -e "USE Solstus; CREATE INDEX idx_pvdata_timestamp ON PVData (_TimeStamp);"
else
  echo -e "\n*** ${Green} Index 'idx_pvdata_timestamp' already exists. ${NC} \n"
fi

# UDEV HidRAW Rules
printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' -
echo -e "\n*** ${Green} Adding udev rules... ${NC} \n"

sudo touch /etc/udev/rules.d/69-inverter.rules
echo 'ATTRS{idVendor}=="0665", ATTRS{idProduct}=="5161",SUBSYSTEMS=="usb", ACTION=="add", MODE="0666",GROUP="plugdev"' | sudo tee --append /etc/udev/rules.d/69-inverter.rules
echo 'SUBSYSTEM=="tty", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6015", SYMLINK+="bmv"' | sudo tee --append /etc/udev/rules.d/69-inverter.rules
echo 'SUBSYSTEM=="tty", ATTRS{idVendor}=="067b", ATTRS{idProduct}=="2303", SYMLINK+="pylon"' | sudo tee --append /etc/udev/rules.d/69-inverter.rules

# Sudoes 
printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' -
echo -e "\n*** ${Green} Adding Solstus Script logic to sudoers... ${NC} \n"

# Backup file first.
sudo cp /etc/sudoers /etc/sudoers.backup.solstus

echo "# Solstus root access Logic" | sudo tee --append /etc/sudoers
echo "www-data ALL=(ALL) NOPASSWD:/home/$CURUSER/html/StartService.php" | sudo tee --append /etc/sudoers
echo "www-data ALL=(ALL) NOPASSWD:/home/$CURUSER/html/SetZeroTier.php" | sudo tee --append /etc/sudoers
echo "www-data ALL=(ALL) NOPASSWD:/home/$CURUSER/html/GetZeroTier.php" | sudo tee --append /etc/sudoers
echo "www-data ALL=(ALL) NOPASSWD:/home/$CURUSER/html/SetZeroTier.sh" | sudo tee --append /etc/sudoers
echo "www-data ALL=(ALL) NOPASSWD:/home/$CURUSER/html/SendReboot.php" | sudo tee --append /etc/sudoers
echo "www-data ALL=(ALL) NOPASSWD:/sbin/reboot, /sbin/halt, /sbin/poweroff" | sudo tee --append /etc/sudoers
echo "www-data ALL=(ALL) NOPASSWD:/bin/systemctl start solstus" | sudo tee --append /etc/sudoers
echo "www-data ALL=(ALL) NOPASSWD:/bin/systemctl stop solstus" | sudo tee --append /etc/sudoers
echo "www-data ALL=(ALL) NOPASSWD:/bin/systemctl restart solstus" | sudo tee --append /etc/sudoers
echo "$CURUSER ALL=(ALL) NOPASSWD:/sbin/reboot, /sbin/halt, /sbin/poweroff" | sudo tee --append /etc/sudoers
echo "$CURUSER ALL=(ALL) NOPASSWD:/home/$CURUSER/updatesolstus.sh" | sudo tee --append /etc/sudoers
echo "$CURUSER ALL=(ALL) NOPASSWD:/bin/systemctl start solstus" | sudo tee --append /etc/sudoers
echo "$CURUSER ALL=(ALL) NOPASSWD:/bin/systemctl stop solstus" | sudo tee --append /etc/sudoers
echo "$CURUSER ALL=(ALL) NOPASSWD:/bin/systemctl restart solstus" | sudo tee --append /etc/sudoers

# User Group 
printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' -
echo -e "\n*** ${Green} Adding user $CURUSER to required groups... ${NC} \n"
sudo usermod -a -G dialout $CURUSER
sudo usermod -a -G www-data $CURUSER

# Install MQTT
printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' -
echo -e "\n*** ${Green} Checking for C++ MQTT libraries ${NC} \n"

if [ "$ArcElf" == "aarch64" ]; then
	MQTTLib=/usr/lib/aarch64-linux-gnu/libQt5Mqtt.so
elif [ "$ArcElf" == "armv7l" ]; then	
	MQTTLib=/usr/lib/arm-linux-gnueabihf/libQt5Mqtt.so
elif [ "$ArcElf" == "x86_64" ]; then
	MQTTLib=/usr/lib/x86_64-linux-gnu/libQt5Mqtt.so
else
	echo -e "${Red} Unsupported OS - We cant continue ${NC}";
	exit 5;
fi

if [ ! -f $MQTTLib ]; then	

	# Get Qt QMake Version on system used
	qmake_version_output=$(qmake --version 2>&1)	
	qmake_version=$(echo "$qmake_version_output" | grep -o 'Using Qt version .*' | awk '{print $4}' | awk -F'.' '{print $1"."$2}')
	
	echo -e "\n"
	echo -e "*** QMake Version: $qmake_version"
	echo -e "\n"
	
	# MQTT On Git to check against
	repository="qt/qtmqtt"
	branch=$qmake_version
	
	url="https://api.github.com/repos/$repository/branches/$branch"

	# Make a GET request to the GitHub API
	response=$(curl -s "$url")

	# Check the HTTP status code to see if the branch exists
	http_status=$(echo "$response" | jq -r '.message')

	if [ "$http_status" == "Branch not found" ]; then
	  echo "Branch $branch does not exist in the $repository repository."	  
	  UseBuildVer="5.15"
	else
	  echo "Branch $branch exists in the $repository repository."
	  UseBuildVer=$qmake_version
	fi

	echo -e "\n*** ${Yellow} MQTT Missing, will compile from sources ${NC}"
	echo -e "***  Compiling C++ MQTT libraries..."
	cd ~
	sudo apt update
	sudo apt install qtbase5-dev qtchooser qt5-qmake qtbase5-dev-tools qt5-qmake-bin qtbase5-private-dev -y
	git clone --branch $UseBuildVer https://github.com/qt/qtmqtt.git
	cd qtmqtt/
	mv examples examples1
	mkdir build
	cd build
	qmake -r ..
	make
	sudo make install
	cd ~
else
	echo -e "\n*** ${Green} C++ MQTT libraries Found...Skipping ${NC}"
fi

# Insatalling WiringPi IF this is a Raspberry PI (Mandatory)
if [ "$ArcElf" == "armv7l" ]; then
	wget https://github.com/WiringPi/WiringPi/releases/download/2.61-1/wiringpi-2.61-1-armhf.deb
	sudo dpkg -i wiringpi-2.61-1-armhf.deb
	sudo rm wiringpi-2.61-1-armhf.deb
	
elif [ "$ArcElf" == "aarch64" ]; then
	
	wget https://github.com/WiringPi/WiringPi/releases/download/2.61-1/wiringpi-2.61-1-arm64.deb
	sudo dpkg -i wiringpi-2.61-1-arm64.deb
	sudo rm wiringpi-2.61-1-arm64.deb
fi

# install Zerotier VPN (Mandatory)
printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' -
echo -e "\n*** ${Green} Installing ZeroTier One VPN used by Solstus... ${NC} \n"
curl -s https://install.zerotier.com | sudo bash

# Stop Apache
sudo systemctl stop apache2

printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' -
echo -e "\n*** ${Green} Installing Solstus files from Micro Fusion servers... ${NC} \n"

# Install Update Script
updatescript=updatesolstus.sh
cd /home/$CURUSER
if [ ! -f $updatescript ]; then
    wget http://www.microfusion.org/Software/solstus/$updatescript
	sudo chmod +x /home/$CURUSER/$updatescript
fi

# Go to Web directory
cd /home/$CURUSER/html

# Install Solstus Application next 
updateFile=Solstus-Update.zip

if [ "$ArcElf" == "aarch64" ] || [ "$ArcElf" == "armv7l" ]; then
	UpdateFileArc="Solstus-Update.zip"	
elif [ "$ArcElf" == "x86_64" ]; then
	UpdateFileArc="Solstus-Update-lx64.zip"
else
	echo -e "${Red} Unsupported OS - Try Ubuntu 22.04 LTS ${NC}";
	exit 6
fi

if [ ! -f $updateFile ]; then
    wget -O Solstus-Update.zip http://www.microfusion.org/Software/solstus/current/$UpdateFileArc
fi

unzip -o Solstus-Update.zip -d /home/$CURUSER/html

rm Solstus-Update.zip
mv /home/$CURUSER/html/Solstus /home/$CURUSER/
mv /home/$CURUSER/html/startsolstus.sh /home/$CURUSER/
sudo chmod +x /home/$CURUSER/Solstus
sudo chmod +x /home/$CURUSER/html/SetZeroTier.sh
sudo chmod +x /home/$CURUSER/startsolstus.sh

# Compile Solstus From Source - Only for Developer. Normal users wont require or, be able to do this
ProjectDir=solstus-dev

if [ "$1" == "dev" ]; then
	
	OKSRC="n"
	echo -e "\n*** ${Yellow} Require Developer Token Skip For Normal Install !!! ${Cyan}"
	read -p "Do you want to download and compile Solstus from source? [y/N]: " dconfirm
	echo -e ${NC}
	
	if [[ "$dconfirm" == "y" ]]; then

		echo -e "\n*** ${Green} Fetching Solstus-Dev C++ project files from Sources ... ${NC} \n"
		printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' -
		cd ~
		mkdir /home/$CURUSER/$ProjectDir		
		wget -O solstus-source.zip http://www.microfusion.org/Software/solstus/current/solstus-source.zip
		# Prompt for Password Developer Token
		echo -e "\n${Cyan}"		
		read -s -p "Please enter Developer Token for the Solstus Development Build Branch: " passw		
		echo -e ${NC}
		# Extract Source code
		unzip -P $passw -o solstus-source.zip -d /home/$CURUSER/$ProjectDir
		
		# Compile build steps IF above steps where completed
		if [ -d $ProjectDir ]; then
			echo -e "\n*** ${Green} Compiling Solstus from Sources ... ${NC}\n"
			printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' -
			cd /home/$CURUSER/solstus-dev
			rm *.o
			touch *
			qmake
			make
			mv Solstus /home/$CURUSER/
			sudo chmod +x /home/$CURUSER/Solstus
			# Cleanup Source code
			cd /home/$CURUSER
			rm -r /home/$CURUSER/$ProjectDir
			rm /home/$CURUSER/solstus-source.zip
		fi
		
	else
		echo -e "${Yellow} Skipping Compile from sources ${NC}";
	fi
fi

# Adjust PHP max upload sized
echo -e "\n*** ${Green} Adjust PHP Upload File sizes ... ${NC} \n"

upload_max_filesize=1024M
post_max_size=1024M
PHPFILEPATH=`php -i | grep /.+/php.ini -oE`

sudo cp $PHPFILEPATH $PHPFILEPATH.bak

for key in upload_max_filesize post_max_size 
do
 sudo sed -i "s/^\($key\).*/\1 = $(eval echo \${$key})/" $PHPFILEPATH
done

#Start Apache
echo -e "\n*** ${Green} Restarting Apache Webserver ... ${NC} \n"
sudo systemctl start apache2

# Systemd Logic

# Check and remove old Systemd service file if exist
if [ -f /etc/systemd/system/solstus.service ]; then
	
	echo -e "\n*** ${Yellow} Found an existing systemd service for Solstus ... \n"
	echo -e ${Cyan}
	read -p "Do you want to remove the existing Systemd service now ? [y/n]: " confirm2	
	echo -e ${NC}
		
	if [[ "$confirm2" == "y" ]]; then
		echo -e "\n${Yellow}Removing Solstus Systemd Service now...${NC}\n"		
		sudo systemctl stop solstus
		sudo systemctl disable solstus
		sudo rm /etc/systemd/system/solstus.service
		sudo systemctl daemon-reload
		sudo systemctl reset-failed
	else
		echo -e "\n*** ${Yellow} Skipping removal of existing systemd service for Solstus ... ${NC} \n"
	fi
fi

if [ ! -f /etc/systemd/system/solstus.service ]; then

	# Install New Systemd service file for Solstus
	echo -e ${Cyan} 
	read -p "Do you want to install a new systemd service for Solstus now ? [y/n]: " confirm3	
	echo -e ${NC}
	
	if [[ "$confirm3" == "y" ]]; then

		# Install New Systemd service file for Solstus
		printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' -
		echo -e "\n*** ${Green} Installing Solstus Systemd service ... ${NC} \n"
		# Create systemd service file for solstus
		sudo touch /etc/systemd/system/solstus.service
		sudo chmod 0777 /etc/systemd/system/solstus.service
		# Populate service directives
		echo -e "[Unit]" | sudo tee --append /etc/systemd/system/solstus.service
		echo -e "Description=Solstus Solar IoT System" | sudo tee --append /etc/systemd/system/solstus.service
		echo -e "After=network.target mysql.service" | sudo tee --append /etc/systemd/system/solstus.service
		echo -e "StartLimitIntervalSec=0" | sudo tee --append /etc/systemd/system/solstus.service
		echo -e '\n' | sudo tee --append /etc/systemd/system/solstus.service
		echo -e "[Service]" | sudo tee --append /etc/systemd/system/solstus.service
		echo -e "Type=simple" | sudo tee --append /etc/systemd/system/solstus.service
		echo -e "Restart=on-failure" | sudo tee --append /etc/systemd/system/solstus.service
		echo -e "RestartSec=1" | sudo tee --append /etc/systemd/system/solstus.service
		echo -e "User=$CURUSER" | sudo tee --append /etc/systemd/system/solstus.service
		echo -e "ExecStart=/home/$CURUSER/startsolstus.sh" | sudo tee --append /etc/systemd/system/solstus.service
		echo -e '\n' | sudo tee --append /etc/systemd/system/solstus.service
		echo -e "[Install]" | sudo tee --append /etc/systemd/system/solstus.service
		echo -e "WantedBy=multi-user.target" | sudo tee --append /etc/systemd/system/solstus.service
		# Set Root permissions for service
		sudo chmod 0644 /etc/systemd/system/solstus.service	
		
	else
		echo -e "\n*** ${Yellow} Skipping installation systemd service for Solstus - You will need to manually start Solstus ... ${NC} \n"
	fi
	
	# Starting Solatus Service Now
	echo -e ${Cyan}
	read -p "Do you want to start the Solstus service now ? [y/n]: " confirm5
	echo -e ${NC}
	
	if [[ "$confirm5" == "y" ]]; then
		echo -e "\n*** ${Green} Starting up Solstus service now... ${NC} \n"			
		sudo systemctl start solstus
	else
		echo -e "\n*** ${Yellow} Skipping systemd service startup for Solstus ... ${NC} \n"
	fi
	
	# Enabling Solstus Auto Start when system boots
	echo -e ${Cyan}
	read -p "Do you want to start the Solstus service every time the system boots ? [y/n]: " confirm6
	echo -e ${NC}
	
	if [[ "$confirm6" == "y" ]]; then	
		echo -e "\n*** ${Green} Enabling Solstus systemd service auto startup at system boot ... ${NC} \n"			
		sudo systemctl enable solstus
	else
		echo -e "\n*** ${Yellow} Skipping systemd service auto startup for Solstus - You will need to manually start Solstus ... ${NC} \n"
	fi
fi

# Firewall rules for Ubuntu only
if [[ "$OSUSED" == "Ubuntu" || "$OSUSED" == *"Ubuntu"* || "$UBUNTU" == *"Ubuntu"* || "$OSUSED" == "Linuxmint" ]]; then
	echo -e "\n*** ${Green} Setting up Firewall rules now... ${NC} \n"
	sudo ufw allow apache 
	sudo ufw allow ssh
	sudo ufw allow 8888/tcp
fi

# Cleanup
echo -e "\n*** ${Green} Cleaning Up ... ${NC} \n"
sudo apt autoremove -y

# Installation complete
echo -e "\n"
printf  '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' -
echo -e "${Green}Solstus IoT Solar is now installed on this system ${NC}\n"
echo -e "Solstus uses systemd service e.g"
echo -e "${Cyan}sudo systemctl start solstus${NC} | ${Cyan}sudo systemctl stop solstus${NC} | ${Cyan}sudo systemctl status solstus${NC}"
echo -e "\n${Green}phpmyadmin login${NC}"
echo -e "---------------------------"
echo -e "phpmyadmin login User: admin"
echo -e "phpmyadmin login Pass: admin"
echo -e "---------------------------"
echo -e "\n${Green}MySQL login${NC}"
echo -e "---------------------------"
echo -e "MySQL login User: admin"
echo -e "MySQL login Pass: admin"
echo -e "---------------------------"
echo -e "\n"
echo -e "Manually start Solstus using ${Cyan}/home/$CURUSER/startsolstus.sh${NC} in terminal"
echo -e "\n"
echo -e "Access Solstus from > ${Cyan}http://localhost${NC} or this PCs IP address\n"

exit 0