#!/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


if [ $# -lt 1 ]; then
	echo "Usage $0 GAME_NAMES_SPACE_SEPARATED"
	exit 1
fi
apt install --yes ncftp 2>/dev/null 1>/dev/null

#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
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
	PACK_VERSION=`cat $ROULETTE/pack.info |jq -r '.Version'`
        echo "Can not fetch FTP_VERSION_FOLDER info from database; defaulting to V$PACK_VERSION"
        VERSION_FOLDER="V$PACK_VERSION"
fi

DESTINATION_PATH=/var/IGP/packages/Games
#WE USE THE ONE FROM common.config;  REMOTE_DIR=PACKAGES/$JURISDICTION/$VERSION_FOLDER
REMOTE_DIR=`eval echo $REMOTE_DIR`
REMOTE_DIR=$REMOTE_DIR/Games
echo "Downloading from remote directory $REMOTE_DIR into $DESTINATION_PATH"

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

RETURN=0; #result 0 - nothing done!
for PACK_NAME in "$@"
do

	REMOTE_FILE=$PACK_NAME".pack"
	if [ $PACK_NAME == "no_reboot" ] ||
	   [ $PACK_NAME == "force_ftp" ] ||
	   [ $PACK_NAME == "force_usb" ] ||
	   [ $PACK_NAME == "reboot" ]; then
		continue;
	fi

	#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"
		
			SOURCE_FILE=`find /media/ -name "$PACK_NAME.pack" -print -quit`
			if [ -f $SOURCE_FILE ] && [ -f $SOURCE_FILE.md5 ] && [ -f $DESTINATION_PATH/$PACK_NAME.pack ]; then 
				if [ "`md5sum $DESTINATION_PATH/$PACK_NAME.pack|cut -d' ' -f1-1`" == "`cat $SOURCE_FILE.md5|cut -d' ' -f1-1`" ]; then 
					echo 
					echo -e "$GREEN""$PACK_NAME already same version as on /media. Skipping transfer...""$NC"
					#continue, but delete update file if it exists, maybe is some strange version
					rm -f $DESTINATION_PATH/$PACK_NAME.pack.update
					RETURN=11 #success copying from media - (MD5 match, no need to copy...)
					continue;
				fi
			fi

			ps -A|grep $SOURCE_FILE
	                if [ $? -ne 0 ]; then #ce igra ne tece, jo odmontiramo in brisemo pack
        	                echo "Umounting $DESTINATION_PATH/$PACK_NAME and removing associated .pack to mind diskspace."
                	        umount $DESTINATION_PATH/$PACK_NAME
                        	rm -rf $DESTINATION_PATH/$PACK_NAME".pack"
	                fi

			#rsync -a -v `find /media/ -name "$PACK_NAME.pack" -print -quit ` $DESTINATION_PATH"/$PACK_NAME.pack.update"
			rsync -a -v $SOURCE_FILE $DESTINATION_PATH"/$PACK_NAME.pack.update"
			if [ $? -eq 0 ]; then
				RETURN=1 #success copying from media
			else
				RETURN=$((100 + $?)) #result + 100 means an error occoured while copying from /media
			fi

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

                	#if error copying, skip..
	                if [ $RETURN -gt 100 ]; then
        	                echo "Update Failed."
                	        continue
	                fi

			chown root:root $DESTINATION_PATH"/$PACK_NAME.pack.update"
			chmod 644 $DESTINATION_PATH"/$PACK_NAME.pack.update"
			echo -e "$GREEN""Update $PACK_NAME done.""$NC"

			#maybe it is better to leave this to restart.., but anyway..
        	        #if game does not exist, rename the pack, this is first install, not update..., or the original package has been deleted, to mind disk space
                	if [ ! -f $DESTINATION_PATH"/$PACK_NAME.pack" ]; then
                        	mv $DESTINATION_PATH"/$PACK_NAME.pack.update" $DESTINATION_PATH"/$PACK_NAME.pack"

	                        #if game not mounted, mount the new pack..
        	                mount|grep $PACK_NAME
#	                       if [ $? -gt 0 ]; then
#       	                if [ $? -gt 0 ]; then
                	                mount -o ro -o loop $DESTINATION_PATH/$PACK_NAME".pack" $DESTINATION_PATH/$PACK_NAME
#                       	fi
	                fi
		else
			echo
			echo -e "$GREEN""Pack $PACK_NAME not found on /media. Skipping ""$NC"
		fi

	else

		echo
        	echo -e "$GREEN""Downloading "$PACK_NAME".pack from FTP...""$NC"
	        echo "Please wait..."

		#pack MD5 - must be FIRST, so that if we fail in downloading Game pack, we will notice it by MD5 failure
		rm -rf $DESTINATION_PATH/$PACK_NAME".pack.update.md5"
        	wget $WGET_OPT -O $DESTINATION_PATH/$PACK_NAME".pack.update.md5" http://dubl7696qavg.cloudfront.net/$REMOTE_DIR/$REMOTE_FILE.md5
#        	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"

		#now test, if download is necesary
		#if we have md5 file to compare, make the compare
		#first test .pack
		if [ -f $DESTINATION_PATH/$PACK_NAME.pack.update.md5 ] && [ -f $DESTINATION_PATH/$PACK_NAME.pack ]; then 
			if [ "`md5sum $DESTINATION_PATH/$PACK_NAME.pack|cut -d' ' -f1-1`" == "`cat $DESTINATION_PATH/$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"
				#continue, but delete update file if it exists, maybe is some strange version
				rm -f $DESTINATION_PATH/$PACK_NAME.pack.update
				RETURN=12 #success copying from ftp
				continue;
			fi
		fi
		#now test also .pack.update, if no reboot was made since last download
		if [ -f $DESTINATION_PATH/$PACK_NAME.pack.update.md5 ] && [ -f $DESTINATION_PATH/$PACK_NAME.pack.update ]; then 
			if [ "`md5sum $DESTINATION_PATH/$PACK_NAME.pack.update|cut -d' ' -f1-1`" == "`cat $DESTINATION_PATH/$PACK_NAME.pack.update.md5|cut -d' ' -f1-1`" ]; then 
				echo 
				echo -e "$GREEN""$PACK_NAME update already same version as on FTP. Skipping transfer... Please reboot.""$NC"
				RETURN=13 #success copying from ftp
				continue;
			fi
		fi

		#Transfer Game pack

		#but first try to remove current version, as we have to mind diskspace
		ps -A|grep $PACK_NAME
		if [ $? -ne 0 ]; then #ce igra ne tece, jo odmontiramo in brisemo pack
			echo "Umounting $DESTINATION_PATH/$PACK_NAME and removing associated .pack to mind diskspace."
			umount $DESTINATION_PATH/$PACK_NAME
			rm -rf $DESTINATION_PATH/$PACK_NAME".pack"
		fi

        	wget $WGET_OPT -c -O $DESTINATION_PATH/$PACK_NAME".pack.update" http://dubl7696qavg.cloudfront.net/$REMOTE_DIR/$REMOTE_FILE
#			echo "wget result=$?"
#        	ncftpget -Z -C -r 1 -u roulette -p updates -t 10 ftp://igpupdates.4knh.com/$REMOTE_DIR/$REMOTE_FILE $DESTINATION_PATH/$PACK_NAME".pack.update"
#		if [ $? -eq 0 ]; then
		if [ $? -le 1 ]; then #vraca 1 tudi ko uspesno prenese!
			RETURN=2 #success copying from ftp
			echo -e "$GREEN""$PACK_NAME downloaded.""$NC"
		else
			RETURN=$((200 + $?)) #result +200 means that error occoured when downloading from ftp
			echo -e "$RED""$PACK_NAME failed. Error downloading http://dubl7696qavg.cloudfront.net/$REMOTE_DIR/$REMOTE_FILE""$NC"
			echo "Not downloaded correctly. Deleting partial file..."
  			rm -f $DESTINATION_PATH/$PACK_NAME".pack.update"
		fi

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

		#maybe it is better to leave this to restart.., but anyway..
		#if game does not exist, rename the pack, this is first install, not update..., or the original package has been deleted, to mind disk space
		if [ ! -f $DESTINATION_PATH"/$PACK_NAME.pack" ]; then
			mv $DESTINATION_PATH"/$PACK_NAME.pack.update" $DESTINATION_PATH"/$PACK_NAME.pack"

			#if game not mounted, mount the new pack.. - this because we umounted in previous steps
			mount|grep $PACK_NAME
			mount -o ro -o loop $DESTINATION_PATH/$PACK_NAME".pack" $DESTINATION_PATH/$PACK_NAME
		fi


		#if error downloading, skip..
		if [ $RETURN -gt 100 ]; then
			echo "Update Failed."
			continue
		fi


		#if we have md5 file to compare, make the compare
		if [ -f $DESTINATION_PATH"/$PACK_NAME.pack.update.md5" ]; then
			if [ -f $DESTINATION_PATH/"$PACK_NAME.pack.update" ]; then 
				if [ "`md5sum $DESTINATION_PATH/$PACK_NAME.pack.update|cut -d' ' -f1-1`" == "`cat $DESTINATION_PATH/$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/$PACK_NAME.pack.update -f
					RETURN=203;
				fi
			else
				echo "Update file was not downloaded."
			fi
		else
			echo "Game MD5 not present on server."
		fi
		echo

	fi
done

exit $RETURN
