#!/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=$1
VERSION_FOLDER=$2
JURISDICTION=$3

PACK_PREFIX=""
if [ -f /var/IGP/backup.chk ]; then
	# If this pack is listed in backup.chk, we have to use the .old. prefix
	if jq -e ".${PACK_NAME}" "/var/IGP/backup.chk" > /dev/null; then
		PACK_PREFIX=".old."
	fi
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

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

echo "Downloading from remote directory $REMOTE_DIR into $DESTINATION_PATH"

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

PACK_REPOSITORY="http://dubl7696qavg.cloudfront.net"

#Transfer pack
wget $WGET_OPT -O $DESTINATION_PATH/$PACK_NAME".deps" $PACK_REPOSITORY/$REMOTE_DIR/$PACK_NAME".deps"
if [ $? -eq 0 ]; then
	echo -e "$GREEN""Got dependency file for $PACK_NAME.""$NC"
else
        echo -e "$GREEN""No dependency file for $PACK_REPOSITORY/$REMOTE_DIR/$PACK_NAME.deps""$NC"
        echo -e "$GREEN""Will continue by using old dependency list or will assume there are no dependencies!""$NC"
fi

if [ -f $DESTINATION_PATH/$PACK_NAME".deps" ]; then
	for line in $(cat $DESTINATION_PATH/$PACK_NAME".deps")
	do
		[[ $@ == *"force_yes"* ]] && PARAMS=$PARAMS" force_yes"
		[[ $@ == *"force_ftp"* ]] && PARAMS=$PARAMS" force_ftp"
		[[ $@ == *"force_usb"* ]] && PARAMS=$PARAMS" force_usb"
		# dependency_only se ne propagira v rekurzivne klice
		./update_pack.sh $line $VERSION_FOLDER $JURISDICTION $PARAMS
		DEPENDENCY_RESULT=$?
		if [ $DEPENDENCY_RESULT -lt 100 ]; then
			echo -e "$GREEN""Successfully updated dependency '$line'.""$NC"
		else
			echo -e "$RED""Could not update dependency '$line' - exit code $DEPENDENCY_RESULT""$NC"
			exit $DEPENDENCY_RESULT #forward error
		fi
	done
fi
[[ $@ == *"dependency_only"* ]] && exit 0 ##nothing to do here # dependency_only se ne propagira v rekurzivne klice


function downloadPack()
{
	#Transfer pack
        wget $WGET_OPT -O $DESTINATION_PATH/$PACK_PREFIX$PACK_NAME".pack.update" $PACK_REPOSITORY/$REMOTE_DIR/$PACK_NAME".pack"
        if [ $? -eq 0 ]; then
		if [ -n $PACK_PREFIX ] && [ -f $DESTINATION_PATH/$PACK_NAME".pack.update" ]; then #popravimo datum .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 $PACK_REPOSITORY/$REMOTE_DIR/$PACK_NAME.pack""$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 $PACK_PREFIX ]; then #poskusimo skopirati tuid .old.
        	        rsync -a -v `find /media/ -name "$PACK_PREFIX$PACK_NAME.pack" -print -quit` $DESTINATION_PATH"/$PACK_PREFIX$PACK_NAME.pack.update"
	        fi
        	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_PREFIX$PACK_NAME.pack.update"
	        chmod 644 $DESTINATION_PATH"/$PACK_PREFIX$PACK_NAME.pack.update"
		if [ -n $PACK_PREFIX ] && [ -f $DESTINATION_PATH/$PACK_NAME".pack.update" ]; then #popravimo datum .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
                wget $WGET_OPT -O $DESTINATION_PATH/$PACK_PREFIX$PACK_NAME".pack.update.md5" $PACK_REPOSITORY/$REMOTE_DIR/$PACK_NAME.pack.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/$PACK_PREFIX$PACK_NAME.pack ]; then
			FILE_TO_CHECK=$DESTINATION_PATH/$PACK_PREFIX$PACK_NAME.pack
		fi
		if [ -f $DESTINATION_PATH/$PACK_PREFIX$PACK_NAME.pack.update ]; then #ce je ze prenesen in ni se reboot-an, preverjamo tega
			FILE_TO_CHECK=$DESTINATION_PATH/$PACK_PREFIX$PACK_NAME.pack.update
		fi

                if [ -f $DESTINATION_PATH/$PACK_PREFIX$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/$PACK_PREFIX$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/$PACK_PREFIX$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/$PACK_PREFIX$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/$PACK_PREFIX$PACK_NAME".pack.update"
	RETURN=244 # means that not enough space
fi

#if error downloading, exit.
if [[ $RETURN -gt 10 ]]; then
	if [[ $RETURN -gt 100 ]]; then
		echo "Update of '$PACK_NAME' failed."
	fi
        exit $RETURN
fi

#if we have md5 file to compare, make the compare
if [ -f $DESTINATION_PATH"/$PACK_PREFIX$PACK_NAME.pack.update.md5" ]; then
	if [ -f $DESTINATION_PATH/"$PACK_PREFIX$PACK_NAME.pack.update" ]; then
                if [ "`md5sum $DESTINATION_PATH/$PACK_PREFIX$PACK_NAME.pack.update|cut -d' ' -f1-1`" == "`cat $DESTINATION_PATH/$PACK_PREFIX$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_PREFIX$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

exit $RETURN
