#! /bin/bash
# -------------
#  This script will update an install automagically
#  Tested on RHEL/CentOS/OEL only
# -------------
# Begin editable section
# Set these variables to actual locations
# -------------
UGCC_ROOT=/ugcc
WWW=/var/www/html
MON=/ugcc/mon
MONO4=y
# -------------
# End user editable section
# Don't modify anything below
# unless you really know what you're doing
# --------------
echo -----------------------------------------
echo Brainless Panel Auto-Updater Version 0.02
echo -----------------------------------------
echo Checking the latest version of Brainless Panel...
if [ ! -f lastver.txt ]
then
	echo 0 > lastver.txt
fi 
VER=`curl http://www.brainless.us/versions/ugcc.txt`

#To force a version to update to, enter it here and uncomment the line
#VER=1.91

iVER=`/bin/csharp -e "Console.Write(Convert.ToInt32($VER * 1000))"`
LASTVER=`cat lastver.txt`
iLASTVER=`/bin/csharp -e "Console.Write(Convert.ToInt32($LASTVER * 1000))"`
echo
echo "Latest version:  $VER | Our version: $LASTVER"
if [ $iVER -gt $iLASTVER ]
then
	echo
	echo
	echo Update Available!
	echo -e  '\033[1;31mWARNING:  Running servers may be shutdown!'
	tput sgr0
	read -p "Proceed?" -n 1 -r
	if [[ ! $REPLY =~ ^[Yy]$ ]]
	then
		exit
	fi
else
	echo No update is available, exiting
	exit
fi
#unalias rm
#unalias cp
echo Stopping services...
systemctl stop ugccmon
systemctl stop httpd
echo Creating backup in /root of $UGCC_ROOT
tar -h -zcf ugccbackup-`date +%Y%m%d-%H%M%S`.tgz -C $UGCC_ROOT --exclude='./servers' --exclude='./deploy' .
echo Downloading update
mkdir -p $UGCC_ROOT/deploy
cd $UGCC_ROOT/deploy
wget http://redirect.brainless.us/UGCC/$VER/Deploy.7z
echo Extracting files from download
7z -y x Deploy.7z
cd Deploy
if [ $MONO4 = y ]
then
	cd WWWPanel-Linux-Mono4
else
	cd WWWPanel-Linux
fi
echo Copying new panel files
cp -rf * $WWW
cd ../Monitor
if [ $MONO4 = y ]
then
	cd Linux-Mono4
else
	cd Linux
fi
echo Copying new monitor files
cp -rf * $MON
cd $UGCC_ROOT
echo Cleaning up....
rm -rf $UGCC_ROOT/deploy
cd ~
echo $VER > lastver.txt
echo Restarting services
systemctl start httpd
systemctl start ugccmon
pdb2mdb /ugcc/www/bin/UGCC.dll
pdb2mdb /ugcc/www/bin/MashToolsSharp.dll
echo Update complete, please login to the panel as an admin user to update database.
