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

#if another instance of this iscrpt is already running, exit
for pid in $(pidof -x slot_update_all.sh); do
    if [ $pid != $$ ]; then
        echo "[$(date)] : slot_update_all.sh : Process is already running with PID $pid"
        exit 1
    fi
done


if [ -x $ROULETTE/sqlexec.sh ]; then

	#set to desired version for the slot-update-all.sh
	echo "select RESULT from SET_PARAM('GLOBAL', 'UPDATE_ALL.sh', 'FTP_VERSION_FOLDER', '', '', 11, 64, 'V6.4');"|/home/ROULETTE/sqlexec.sh
else
	echo
	echo
	echo "WARNING: VERSION AND JURISDICTION CAN NOT BE SET in DB."
	echo "UPDATE WILL BE FOR DEFAULT VERSION AND DEFAULT JURISDICTION."
fi

echo nameserver 8.8.8.8 > /etc/resolv.conf
echo nameserver 8.8.4.4 >> /etc/resolv.conf
echo nameserver 1.1.1.1 >> /etc/resolv.conf

#zabelezimo si, da smo priceli z update-all. Sele ko bomo vse dokoncno poupdate-ali, se bo ta datoteka izbrisala
#IGP-init pa preverja ce ta datoteka obstaja, in ce obstaja, nas bo ponovno poklicala
if [ -z "$UPDATE_ALL_IN_PROGRESS" ]; then
#default location
	UPDATE_ALL_IN_PROGRESS='/var/IGP/.update_all_in_progress'
fi
if [ -f $UPDATE_ALL_IN_PROGRESS ]; then
	echo `date`": Update all restarted, some packages might not beed successfully updated from previous run." >> $UPDATE_ALL_IN_PROGRESS
else
	echo `date`": Update all started. Will update all packages on this system." >> $UPDATE_ALL_IN_PROGRESS
fi


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

#preberemo jurisdikcijo, na FTP-ju bomo iskali to mapo
echo
if [ -x $ROULETTE/sqlexec.sh ]; then

	#set to desired version for the slot-update-all.sh
	echo "select RESULT from SET_PARAM('GLOBAL', 'UPDATE_ALL.sh', 'FTP_VERSION_FOLDER', '', '', 11, 64, 'V6.4');"|/home/ROULETTE/sqlexec.sh

        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 "We will update games available for JURISDICTION=$JURISDICTION"
        else
                echo "Can not fetch JURISDICTION info; will update games for JURISDICTION=DEFAULT"
                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 core pack is not mounted,.., CAN NOT DETERMINE JURISDICTION AND PACK VERSION"
        JURISDICTION=DEFAULT
        PACK_VERSION=6.4
        VERSION_FOLDER="V$PACK_VERSION"
        echo "DEFAULTING TO: JURISDICTION=$JURISDICTION and VERSION=$VERSION_FOLDER"
fi

#Zaklenem SLOT, dokler traja update, igranje ni mogoce
#echo -e "$RED""****LOCKING PLAY with OUT_OF_ORDER_LOCK until update is complete""$NC"
#echo OUT_OF_ORDER_LOCK > /home/IGP/terminal_home/10.5.10.1/CMD/command.file
#OBSOLETE-we lock each game separately


#mark the update in progress
echo "select RESULT from SET_PARAM('PLATFORM_1', 'UPDATE_ALL.sh', 'SOFTWARE_VERSION', '', '', 11, 0, 'Update started at `date`. Downloading...');"|/home/ROULETTE/sqlexec.sh

apt update
apt --assume-yes install libstdc++-9-dev libstdc++6 resolvconf nmap iotop
apt autoremove --assume-yes

#configure resolvconf
#to naredi link na /etc/resolv.conf v /var/run/resolv.conf
/usr/bin/expect<<EOF
spawn dpkg-reconfigure -f readline resolvconf
expect "updates?" { send "Yes\r" }
expect "dynamic files?" { send "Yes\r" }
EOF
systemctl start resolvconf.service
systemctl enable resolvconf.service
systemctl status resolvconf.service
echo nameserver 8.8.8.8 > /etc/resolvconf/resolv.conf.d/head
echo nameserver 8.8.4.4 >> /etc/resolvconf/resolv.conf.d/head
echo nameserver 1.1.1.1 >> /etc/resolvconf/resolv.conf.d/head
resolvconf --enable-updates
resolvconf -u



#delete obsolete records from MULTIGAME_CONFIG
echo "delete from MULTIGAME_CONFIG where CLIENT_ID='GLOBAL';"|/home/ROULETTE/sqlexec.sh
echo "update languages set VISIBLE=1 where LANG_ID=23"|/home/IGP/sqlexec.sh

#set PUERTO_RICO costumization
echo "select RESULT from SET_PARAM('GLOBAL', 'UPDATE_ALL.sh', 'JURISDICTION', '', '', 11, NULL, 'PERU');"|/home/ROULETTE/sqlexec.sh
echo "select RESULT from SET_PARAM('GLOBAL', 'UPDATE_ALL.sh', 'BILL_CURRENCY', '', '', 11, NULL, 'PEN');"|/home/ROULETTE/sqlexec.sh
echo "select RESULT from SET_PARAM('GLOBAL', 'UPDATE_ALL.sh', 'GAMES_ORDER', '', '', 11, NULL, '4');"|/home/ROULETTE/sqlexec.sh

echo "select RESULT from SET_PARAM('GLOBAL', 'UPDATE_ALL.sh', 'DEF_LANGUAGE', '', '', 11, NULL, '23');"|/home/ROULETTE/sqlexec.sh
echo "select RESULT from SET_PARAM('GLOBAL', 'UPDATE_ALL.sh', 'MENU_LANGUAGE', '', '', 11, NULL, '11');"|/home/ROULETTE/sqlexec.sh
#echo "delete FROM CONFIGURATION WHERE ATTR_NAME like 'KEY\_%' ESCAPE '\';"|/home/ROULETTE/sqlexec.sh


#stability patch, fix the wrong value for NUMBER_OF_LAST_GAMES
echo "select RESULT from SET_PARAM('TERMINAL', 'UPDATE_ALL.sh', 'NUMBER_OF_LAST_GAMES', '', '', 11, 500, '500');"|/home/ROULETTE/sqlexec.sh
find /var/IGP/terminal_home/10.5.10.1/Games/Roulette -type f -mtime +30 -delete
find /var/IGP/terminal_home/10.5.10.1/Games/Roulette00 -type f -mtime +30 -delete
wget -q http://igpupdates.4knh.com/LANDBASE_ROULETTE/RELEASE/reset_terminal_home_V6.sh -O /var/IGP/packages/reset_terminal_home.sh
chmod 777 /var/IGP/packages/reset_terminal_home.sh
/var/IGP/packages/reset_terminal_home.sh FORCE_YES

#is this the first time that V6 is installing over V7??
if [ -h /var/IGP/slot_update_all.sh ]; then
        #file exists, so where is this file pointed, to V6 or V7?
        readlink -f /var/IGP/slot_update_all.sh |grep V7 
        RES=$?
else
        #if file does not exist, it should be an old version of V6, so NO
        RES=1
fi
if [ $RES -eq 0 ]; then
        #KILLALL
        killall -9 topscreen
        killall -9 igplatform

        #schedule DBRepairLevel2, to je nujno zaradi spremembe sym/engines/
        echo > $FC5/RouletteMaster/EMPTY_DATABASE/.repair_db_pending2.cmd

        #pri update-u moram brisati iz instances
        echo "delete from INSTANCES" | $ROULETTE/sqlexec.sh

        #delete V6 Games
        mv /var/IGP/packages/Games /var/IGP/packages/GamesV7_delme
        mkdir -p /var/IGP/packages/Games
fi

wget -q http://igpupdates.4knh.com/LANDBASE_ROULETTE/RELEASE/update_core.sh -O /var/IGP/packages/update_core.sh
wget -q http://igpupdates.4knh.com/LANDBASE_ROULETTE/RELEASE/update_checksummer.sh -O /var/IGP/packages/update_checksummer.sh
wget -q http://igpupdates.4knh.com/LANDBASE_ROULETTE/RELEASE/update_game.sh -O /var/IGP/packages/Games/update_game.sh
wget -q http://igpupdates.4knh.com/LANDBASE_ROULETTE/RELEASE/IGP-init.sh -O /var/IGP/IGP-init.sh
chmod 777 /var/IGP/IGP-init.sh
chmod 777 /var/IGP/packages/Games/update_game.sh
chmod 777 /var/IGP/packages/update_checksummer.sh
chmod 777 /var/IGP/packages/update_core.sh


RESTART_REQUIRED=0
UPDATE_FULLY_SUCCEEDED=1

echo "Updating Core..."; 
echo `date`": Updating Core...." >> $UPDATE_ALL_IN_PROGRESS
cd /var/IGP/packages
/var/IGP/packages/update_core.sh force_yes no_reboot
UPDATE_RESULT=$?
if [ $UPDATE_RESULT -eq 1 ] | [ $UPDATE_RESULT -eq 2 ]; then #success
	RESTART_REQUIRED=1
else
	UPDATE_FULLY_SUCCEEDED=0
fi
#reget backup.chk for the current jurisdiction
wget -q http://igpupdates.4knh.com/PACKAGES_IGP/$JURISDICTION/$VERSION_FOLDER/backup.chk -O /var/IGP/backup.chk

##copy game settings to machine
#/var/IGP/packages/restore_packages.sh


cd /var/IGP/packages/Games
NUMBER_OF_GAMES=0
#for Game in $(echo "select distinct GAME_NAME from multigame_config where VALIDATION is not null and AVAILABLE = 1"|/home/ROULETTE/sqlexec.sh | grep -v GAME_NAME|grep -v ===|grep -v "SQL OK"|awk 'NF')
#for Game in $(echo "select distinct MULTIGAME_CONFIG.GAME_NAME from multigame_config left outer join GAMES on MULTIGAME_CONFIG.GAME_ID=GAMES.GAME_ID where VALIDATION is not null and VALIDATION not like '' and AVAILABLE = 1 and ENABLED = 1 and (APPROVED_FOR like '%$JURISDICTION%' or APPROVED_FOR is null)" | /home/ROULETTE/sqlexec.sh | grep -v GAME_NAME|grep -v ===|grep -v "SQL OK"|awk 'NF')
for Game in $(echo "AfricanSunset AtlantisWorld BurningFlame Caligula CastleBlood ChineseZodiac CircusOfHorror DragonKing DynamiteFruits ElBisonte ElToreo FourSymbols GoldOfRa JoanOfArc KingOfMonkeys QueenOfTheSeas Roulette00 SlotOfMoney SpartansLegacy StormingFlame ThunderBird TigerHeart") 
do 
        echo "Updating $Game..."; 
	echo `date`": Updating $Game...." >> $UPDATE_ALL_IN_PROGRESS
#first we check if game is running, if the game can be updated,
#	GAMES_PATH=/var/IGP/packages/Games
#	umount $GAMES_PATH/$Game
#	UMOUNT_FAILED=$?
	ps -A|grep $Game
	GAME_NOT_RUNNING=$?
	mount|grep $Game
	NOT_MOUNTED=$?
	if [ $NOT_MOUNTED -eq 1 ] || [ $GAME_NOT_RUNNING -eq 1 ]; then #[ $UMOUNT_FAILED -eq 0 ]; then
	#if umount success, we start the update, otherwise we will skip this game and retry after reboot
		#disable the game in database and inform the platform about the change
		GAME_DISPLAY_TYPE=0
		if [ -x $ROULETTE/sqlexec.sh ]; then
			GAME_DISPLAY_TYPE=`echo "select DISPLAY_TYPE from MULTIGAME_CONFIG where GAME_NAME='$Game'" | $ROULETTE/sqlexec.sh |head -6|tail -1|sed 's/^M$//'|sed 's/[ ^t]*$//'`
			echo "update MULTIGAME_CONFIG set ENABLED=0 where GAME_NAME='$Game'"|$ROULETTE/sqlexec.sh  2>/dev/null 1>/dev/null
#ne podpirajo stare platforme 4ke echo "update MULTIGAME_CONFIG set DISPLAY_TYPE=3 where GAME_NAME='$Game'"|$ROULETTE/sqlexec.sh  2>/dev/null 1>/dev/null
			echo "execute procedure CMD_NEW('slot_update_all', 'PLATFORM', 'GAME_UPDATE', NULL, NULL, NULL, 10)"| $ROULETTE/sqlexec.sh  2>/dev/null 1>/dev/null
		fi

	        /var/IGP/packages/Games/update_game.sh $Game no_reboot
		UPDATE_RESULT=$?
		if [ $UPDATE_RESULT -eq 1 ] || [ $UPDATE_RESULT -eq 2 ] || [ $UPDATE_RESULT -eq 11 ] || [ $UPDATE_RESULT -eq 12 ] || [ $UPDATE_RESULT -eq 13 ]; then #success
			if [ $UPDATE_RESULT -eq 1 ] || [ $UPDATE_RESULT -eq 2 ];then
				RESTART_REQUIRED=1 #samo ce je bil dejanski prenos je RESTART_REQUIRED
			fi

			echo -e "$GREEN""**$Game update complete.""$NC"
			echo `date`": $Game update complete." >> $UPDATE_ALL_IN_PROGRESS
		else
			if [ $UPDATE_RESULT -gt 200 ]; then
				echo -e "$RED"": Can not find $Game on update server. Retrying doesn't make sense.""$NC"
				echo `date`": Can not find $Game on update server. Retrying doesn't make sense." >> $UPDATE_ALL_IN_PROGRESS
			else
				echo -e "$RED"": $Game update failed. Will retry after reboot...""$NC"
				echo `date`": $Game update failed. Will retry after reboot..." >> $UPDATE_ALL_IN_PROGRESS
				UPDATE_FULLY_SUCCEEDED=0
			fi
		fi
		let "NUMBER_OF_GAMES++"


		#enable the game again
		if [ -x $ROULETTE/sqlexec.sh ]; then
			echo "update MULTIGAME_CONFIG set ENABLED=1 where GAME_NAME='$Game'"|$ROULETTE/sqlexec.sh 2>/dev/null 1>/dev/null
#stare platforme ne podpirajo 4ke echo "update MULTIGAME_CONFIG set DISPLAY_TYPE=$GAME_DISPLAY_TYPE where GAME_NAME='$Game'"|$ROULETTE/sqlexec.sh 2>/dev/null 1>/dev/null
			echo "execute procedure CMD_NEW('slot_update_all', 'PLATFORM', 'GAME_UPDATE', NULL, NULL, NULL, 10)"| $ROULETTE/sqlexec.sh 2>/dev/null 1>/dev/null
		fi
	else

		echo
		echo 
		echo -e "$RED""Unable to update $Game. Is the game running? Update will retry later...""$NC"
		echo `date`": Unable to update $Game. Is the game running? Update will retry later..." >> $UPDATE_ALL_IN_PROGRESS
		UPDATE_FULLY_SUCCEEDED=0 #spodaj bomo popravili, v primeru, da je checksum enak in download ni potreben

#predno zagotovo recemo da je igra potrebna za update
#gremo preveriti, ali je mogoce ta igra ze posodobljena, ce je jo lahko preskocimo, sicer pa oznacimo pending za naslednji poskus
		#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
		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"
		PACK_NAME=$Game
		REMOTE_FILE=$PACK_NAME".pack"

		#zdaj preverimo, ali je mogoce ta igra ze zadnja verzija in ce je, jo lahko preskocimo
                rm -rf $DESTINATION_PATH/$PACK_NAME".pack.update.md5"
                wget $WGET_OPT -O $DESTINATION_PATH/$PACK_NAME".pack.update.md5" http://igpupdates.4knh.com/$REMOTE_DIR/$REMOTE_FILE.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 
				echo -e "$RED""Pack for $Game is already latest version by MD5 result. Skipping...""$NC"
				echo `date`": Pack for $Game is already latest version by MD5 result. Skipping..." >> $UPDATE_ALL_IN_PROGRESS
				UPDATE_FULLY_SUCCEEDED=1
                        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 
				echo -e "$RED""Pack for $Game is already latest version by MD5 result. Skipping... Please reboot.""$NC"
				echo `date`": Unable to update $Game. Is the game running? Update will retry later... Please reboot." >> $UPDATE_ALL_IN_PROGRESS
				UPDATE_FULLY_SUCCEEDED=1
                        fi
                fi
	fi
done
if [ 0 -eq $NUMBER_OF_GAMES ]; then

	echo 
	echo "No games to update/download."
fi



#echo -e "$RED""****UNLOCKING PLAY - update is complete""$NC"
#echo OUT_OF_ORDER_UNLOCK > /home/IGP/terminal_home/10.5.10.1/CMD/command.file
#OBSOLETE-we lock each game separately

if [ $RESTART_REQUIRED -gt 0 ]; then
	echo -e "$RED""Some games or core were updated. Requesting restart of system!""$NC"
	##REQUEST RESART ni typo, je tako v binaries, nove verzije podpirajo oboje RESTART in RESART
	echo "execute procedure CMD_NEW('update', 'PLATFORM', 'REQUEST_RESART', NULL, NULL, NULL, 3)" |/home/ROULETTE/sqlexec.sh 2>/dev/null 1>/dev/null

	#mark the update in restart required
	echo "select RESULT from SET_PARAM('PLATFORM_1', 'UPDATE_ALL.sh', 'SOFTWARE_VERSION', '', '', 11, 0, 'Updating complete, please restart.');"|/home/ROULETTE/sqlexec.sh
fi

if [ $UPDATE_FULLY_SUCCEEDED -gt 0 ]; then
	echo `date`": Update complete. All packages are up to date." >> $UPDATE_ALL_IN_PROGRESS
	echo `date`": Terminating update script." >> $UPDATE_ALL_IN_PROGRESS
	cat $UPDATE_ALL_IN_PROGRESS >> /var/IGP/update_history.log
	rm -rf $UPDATE_ALL_IN_PROGRESS
else
	echo "Some games failed to update, please retry the update manually..."
	echo `date`": Some games failed to update, please retry the update manually..." >> $UPDATE_ALL_IN_PROGRESS
#	eco "Some games failed to update, will retry the update after restart..."
#	echo `date`": Some games failed to update, will retry the update after restart..." >> $UPDATE_ALL_IN_PROGRESS
#vseeno odnehamo, ker to ponavljanje lahko kdaj nagaja	
	cat $UPDATE_ALL_IN_PROGRESS >> /var/IGP/update_history.log
	rm -rf $UPDATE_ALL_IN_PROGRESS

fi

echo -e "$GREEN""Script done.""$NC"
exit 0
