#!/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
PACK_NAME=checksummer

#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
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
	        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
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`
else
        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/$PACK_NAME.pack.update.md5 1>/dev/null 2>/dev/null

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"* ]]; 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 [ $? -eq 0 ]; then
        	RETURN=1 #success copying from media
        else
                RETURN=$((100 + $?)) #result + 100 means an error occoured while copying from /media
        fi
        chown root:root $DESTINATION_PATH"/$PACK_NAME.pack.update"
        chmod 644 $DESTINATION_PATH"/$PACK_NAME.pack.update"
        echo
        echo -e "$GREEN""$PACK_NAME updated from /media ""$NC"
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
                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
                                exit $RETURN;
                        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
                                exit $RETURN;
                        fi
                fi

		#Transfer pack
                wget $WGET_OPT -O $DESTINATION_PATH/$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/$PACK_NAME".pack.update"
                if [ $? -le 1 ]; then #wget vcasih vraca 1 tudi za pravilno prenesene datoteke
#                if [ $? -eq 0 ]; then
                        RETURN=2 #success over ftp
                        echo -e "$GREEN""Update $PACK_NAME done.""$NC"
                else
                        RETURN=$((200 + $?)) #failed over ftp
			echo -e "$RED""Failure while trying to access http://dubl7696qavg.cloudfront.net/$REMOTE_DIR/$REMOTE_FILE""$NC"
                fi
	else
        	exit 1 #ans=no
	fi
fi

#if error downloading, exit.
if [ $RETURN -gt 100 ]; then
        echo Update failed.
        exit $RETURN
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

#if game does not exist, rename the pack, this is first install, not update...
if [ ! -f $DESTINATION_PATH"/$PACK_NAME.pack" ]; then
        mv $DESTINATION_PATH"/$PACK_NAME.pack.update" $DESTINATION_PATH"/$PACK_NAME.pack"
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

