#!/bin/bash
. /home/ROULETTE/common.config #here is configuration of ROULETTE and FC5 locations


GREEN='\033[0;32m' #red
RED='\033[0;31m' #red
NC='\033[0m' # No Color

DESTINATION_PATH=/var/IGP/packages

if [ -f $ROULETTE/pack.info ]; then
	PACK_NAME=`cat $ROULETTE/pack.info |jq -r '.PackName'`
	if [ "$PACK_NAME" == "null" ]; then
		PACK_NAME=""
	fi
fi

if [[ -z "$PACK_NAME" ]]; then
#     	echo
#        echo "Please enter pack name to download from FTP(uppercase, lowercase is important!)."
#       	echo "Example: 'core_gameart' or  'core_roulette_imaxa' or 'core_lady_enigma'[core_gameart]:"
#        read PACK_NAME
#       	[[ -z $PACK_NAME ]] && PACK_NAME="core_gameart" && echo $PACK_NAME #default core_gameart
#        echo
echo "PackName was not found in pack.info, defaulting to core_gameart...."
PACK_NAME=core_gameart
fi
echo "Got PackName= $PACK_NAME . ok.."


if [ -f /var/IGP/backup.chk ]; then
TEN='.old.'
#else
#TEN=''
fi

#TERM je unknown ko se zaganjamo iz beanshell iz symmetric-ds-a je TERM= "unknown", ce pa iz lxterminala je TERM=xterm-256color
#if [ "$TERM" = "unknown" ]; then
if [[ "$TERM" == *"xterm"* ]]; then
	WGET_OPT=" "
else
        #gremo v quiet, ce nismo iz xterm. V primeru ko ni terminala, se zabase output in se prenos ne konca
	WGET_OPT=" -q "
fi

#preberemo jurisdikcijo, na FTP-ju bomo iskali to mapo
echo
PACK_VERSION=`cat $ROULETTE/pack.info |jq -r '.Version'`

if [ -x $ROULETTE/sqlexec.sh ]; then
	JURISDICTION=`echo "select coalesce(RES_STR_VALUE, '') from GET_PARAM('GLOBAL', 'JURISDICTION', 11)" | $ROULETTE/sqlexec.sh |head -6|tail -1|sed -e 's/  *$//'|sed 's/^M$//'|sed 's/[ ^t]*$//'`
	if [ -n "$JURISDICTION" ]; then
        	echo "Downloading packages for JURISDICTION=$JURISDICTION"
	else
        	echo "Can not fetch JURISDICTION info; downloading from DEFAULT source"
	        JURISDICTION=DEFAULT
	fi
	VERSION_FOLDER=`echo "select coalesce(RES_STR_VALUE, '') from GET_PARAM('GLOBAL', 'FTP_VERSION_FOLDER', 11)" | $ROULETTE/sqlexec.sh |head -6|tail -1|sed -e 's/  *$//'|sed 's/^M$//'|sed 's/[ ^t]*$//'`
	if [ -n "$VERSION_FOLDER" ]; then
        	echo "Downloading packages for VERSION=$VERSION_FOLDER"
	else
	        echo "Can not fetch FTP_VERSION_FOLDER info from database; defaulting to V$PACK_VERSION"
        	VERSION_FOLDER="V$PACK_VERSION"
	fi
else
	echo "WARNING: No pack is mounted,.., CAN NOT DETERMINE JURISDICTION AND PACK VERSION"
	JURISDICTION=DEFAULT
	PACK_VERSION=7.2
       	VERSION_FOLDER="V$PACK_VERSION"
	echo "DEFAULTING TO: JURISDICTION=$JURISDICTION and VERSION=$VERSION_FOLDER"
fi

#WE USE THE ONE FROM common.config;  REMOTE_DIR=PACKAGES/$JURISDICTION/$VERSION_FOLDER
if [ -f /home/ROULETTE/common.config ]; then
	REMOTE_DIR=`eval echo $REMOTE_DIR`
fi

if [ -z "$REMOTE_DIR" ]; then 
        REMOTE_DIR=PACKAGES/$JURISDICTION/$VERSION_FOLDER
fi
REMOTE_FILE=$PACK_NAME".pack"
echo "Downloading from remote directory $REMOTE_DIR into $DESTINATION_PATH"


#delete previous MD5 files
rm -f $DESTINATION_PATH/$TEN$PACK_NAME.pack.update.md5 1>/dev/null 2>/dev/null

./update_checksummer.sh $@ no_reboot
RETURN_CHECKSUMMER=$?

function downloadPack()
{
	#Transfer pack
        wget $WGET_OPT -O $DESTINATION_PATH/$TEN$PACK_NAME".pack.update" http://dubl7696qavg.cloudfront.net/$REMOTE_DIR/$REMOTE_FILE
#        ncftpget -Z -C -r 1 -u roulette -p updates -t 10 ftp://igpupdates.4knh.com/$REMOTE_DIR/$REMOTE_FILE $DESTINATION_PATH/$TEN$PACK_NAME".pack.update"
        if [ $? -le 1 ]; then #prej -eq 0 za ncftpget, wget pa vraca lahko kdaj tudi 1, kljub pravilno dowloadanemu file-u
#        if [ $? -eq 0 ]; then
	        #delete the FIRSTRUN file, to make sure firstrun.sh will be exectued for same versions
#                FIRSTRUN="/var/IGP/.gacore_firstrun_"$PACK_VERSION
#FIRSTRUN je deklariran v common.config
                rm -rf $FIRSTRUN
		if [ -n $TEN ] && [ -f $DESTINATION_PATH/$PACK_NAME".pack.update" ]; then #popravimo datum core.pack, ker je old.
        		touch $DESTINATION_PATH/$PACK_NAME".pack.update"
		fi

                echo -e "$GREEN""Update $PACK_NAME done.""$NC"
                return 2 #success over ftp

        else
                echo -e "$RED""Failure while trying to access http://dubl7696qavg.cloudfront.net/$REMOTE_DIR/$REMOTE_FILE""$NC"
                return $((200 + $?)) #error over ftp
        fi
}

RETURN=0 #nothing done
#first try to locate the file on usb stick
if [[ -n "`find /media/ -name "$PACK_NAME.pack" -print -quit|grep ".pack"`" ]] && [[ $@ != *"force_ftp"* ]] || [[ $@ == *"force_usb"* ]]; then
	if [[ -n "`find /media/ -name "$PACK_NAME.pack" -print -quit|grep ".pack"`" ]]; then
		echo
		echo -e "$GREEN""$PACK_NAME.pack found on /media, copying...""$NC"
	        rsync -a -v `find /media/ -name "$PACK_NAME.pack" -print -quit` $DESTINATION_PATH"/$PACK_NAME.pack.update"
	        if [ -n $TEN ]; then #poskusimo skopirati tuid .old.
        	        rsync -a -v `find /media/ -name "$TEN$PACK_NAME.pack" -print -quit` $DESTINATION_PATH"/$TEN$PACK_NAME.pack.update"
	        fi
        	if [ $? -eq 0 ]; then
	        	RETURN=1 #success copying from media

			#delete the FIRSTRUN file, to make sure firstrun.sh will be exectued for same versions
			#FIRSTRUN=/var/IGP/.gacore_firstrun_`cat $ROULETTE/pack.info |jq -r '.Version'`
			rm -rf $FIRSTRUN
        	else
        		RETURN=$((100 + $?)) #result + 100 means an error occoured while copying from /media
	        fi
        	chown root:root $DESTINATION_PATH"/$TEN$PACK_NAME.pack.update"
	        chmod 644 $DESTINATION_PATH"/$TEN$PACK_NAME.pack.update"
		if [ -n $TEN ] && [ -f $DESTINATION_PATH/$PACK_NAME".pack.update" ]; then #popravimo datum core.pack, ker je old.
        		touch $DESTINATION_PATH/$PACK_NAME".pack.update"
		fi

		echo
		echo -e "$GREEN""$PACK_NAME updated from /media ""$NC"
	else
		echo
		echo -e "$GREEN""$PACK_NAME not found on /media. Nothing done ""$NC"
	fi
else
#	apt install --yes ncftp 2>/dev/null 1>/dev/null
	echo
	echo "Download latest version of $PACK_NAME from FTP [YES,no]?"
	[[ $@ == *"force_yes"* ]] && ans="yes"
	[[ $@ != *"force_ftp"* ]] && [[ -z $ans ]] && read ans
	[[ -z $ans ]] && ans="yes" && echo $ans #default
	if [ $ans == "yes" ] || [ $ans == "YES" ]; then
	        echo -e "$GREEN""Downloading "$PACK_NAME".pack from FTP...""$NC"
        	echo "Please wait..."

		#pack MD5 - must be FIRST, if we fail to completely download Game pack, we will notice it by MD5 failure
#                ncftpget -Z -C -r 1 -u roulette -p updates -t 10 ftp://igpupdates.4knh.com/$REMOTE_DIR/$REMOTE_FILE.md5 $DESTINATION_PATH/$PACK_NAME".pack.update.md5"
                wget $WGET_OPT -O $DESTINATION_PATH/$TEN$PACK_NAME".pack.update.md5" http://dubl7696qavg.cloudfront.net/$REMOTE_DIR/$REMOTE_FILE.md5

                #now test, if download is necesary
                #if we have md5 file to compare, make the compare
                #first test .pack
		FILE_TO_CHECK="NO_LOCAL_FILE";
		if [ -f $DESTINATION_PATH/$TEN$PACK_NAME.pack ]; then
			FILE_TO_CHECK=$DESTINATION_PATH/$TEN$PACK_NAME.pack
		fi
		if [ -f $DESTINATION_PATH/$TEN$PACK_NAME.pack.update ]; then #ce je ze prenesen in ni se reboot-an, preverjamo tega
			FILE_TO_CHECK=$DESTINATION_PATH/$TEN$PACK_NAME.pack.update
		fi

                if [ -f $DESTINATION_PATH/$TEN$PACK_NAME.pack.update.md5 ] && [ -f $FILE_TO_CHECK ]; then
		echo
		echo "Calculating MD5SUM for file $FILE_TO_CHECK"
			if [ "`md5sum $FILE_TO_CHECK|cut -d' ' -f1-1`" == "`cat $DESTINATION_PATH/$TEN$PACK_NAME.pack.update.md5|cut -d' ' -f1-1`" ]; then
                                echo
                                echo -e "$GREEN""$PACK_NAME already same version as on FTP. Skipping transfer...""$NC"

				if [ "$FILE_TO_CHECK" = "$DESTINATION_PATH/$TEN$PACK_NAME.pack.update" ]; then
					RETURN=13 #.pack.update same as on FTP, already downloaded, not rebooted
				else
	                                RETURN=12 #.pack same as on FTP
				fi
			else
				downloadPack
				RETURN=$?
                        fi
		else
			echo "Could not find $DESTINATION_PATH/$TEN$PACK_NAME.pack.update.md5 or $FILE_TO_CHECK, skipping version check! Downloading anyway..."
			downloadPack
			RETURN=$?
                fi

	else
		exit 1 #ans=no
	fi
fi

if (( `df -h -k --output=avail / | tail -n 1` < 1000000 )); then
        echo "NOT ENOUGH SPACE! Deleting downloaded file..."
        rm -f $DESTINATION_PATH/$TEN$PACK_NAME".pack.update"
	RETURN=244 # means that not enough space
fi

#if error downloading, exit.
if [[ $RETURN -gt 10 ]] && ( [[ $RETURN_CHECKSUMMER -ne 1 ]] || [[ $RETURN_CHECKSUMMER -ne 2 ]]); then
	if [[ $RETURN -gt 100 ]]; then
		echo Update failed.
	fi
        exit $RETURN
elif [[ $RETURN_CHECKSUMMER -eq 1 ]] || [[ $RETURN_CHECKSUMMER -eq 2 ]]; then
	if [[ $RETURN -gt 10 ]]; then
		exit $RETURN_CHECKSUMMER;
	fi
elif [ $RETURN -gt 100 ]; then
	echo Checksummmer updated.
	exit $RETURN_CHECKSUMMER
fi

#if we have md5 file to compare, make the compare
if [ -f $DESTINATION_PATH"/$TEN$PACK_NAME.pack.update.md5" ]; then
	if [ -f $DESTINATION_PATH/"$TEN$PACK_NAME.pack.update" ]; then
                if [ "`md5sum $DESTINATION_PATH/$TEN$PACK_NAME.pack.update|cut -d' ' -f1-1`" == "`cat $DESTINATION_PATH/$TEN$PACK_NAME.pack.update.md5|cut -d' ' -f1-1`" ]; then
                  	echo
                        echo -e "$GREEN""Updated $PACK_NAME MD5 correct.""$NC"
                else
                        echo
                        echo -e "$RED""Downloaded MD5 Fail. Removing corrupted file...""$NC"
                        rm $DESTINATION_PATH/$TEN$PACK_NAME.pack.update -f
                        RETURN=203;
                fi
        else
                echo "Update file was not downloaded."
        fi
else
        echo "Pack MD5 not present on server."
fi
echo

#if game does not exist, rename the pack, this is first install, not update...
if [ ! -f $DESTINATION_PATH"/$TEN$PACK_NAME.pack" ]; then
        mv $DESTINATION_PATH"/$TEN$PACK_NAME.pack.update" $DESTINATION_PATH"/$TEN$PACK_NAME.pack"

	rm /var/IGP/.*core_firstrun_* -rf #s tem zagotovimo, da se bo ob prvem zagonu paketa posodobilo vse datoteke iz pack_firstrun
fi


if [[ $@ != *"no_reboot"* ]]; then
	if [[ $@ == *"reboot"* ]]; then
		ans=yes
	else
		echo
		echo "REBOOT [yes,NO]?"
		read ans
	fi
	[[ -z $ans ]] && ans="no" && echo $ans #default
	if [ $ans == "yes" ] || [ $ans == "YES" ]; then
		if [ -f /var/IGP/ext/ultra_fast_reboot.sh ]; then
			/var/IGP/ext/ultra_fast_reboot.sh
		elif [ -f /home/IGP/ultra_fast_reboot.sh ]; then
			/home/IGP/ultra_fast_reboot.sh
		else 
			init 6
		fi
	fi
fi

exit $RETURN
