#!/usr/bin/sudo /bin/bash
. /home/ROULETTE/common.config #here is configuration of ROULETTE and FC5 locations
. /home/ROULETTE/flavour.config #here is configuration of ROULETTE and FC5 locations
[ -f $VARIGP/common.config.override ] && . $VARIGP/common.config.override

echo "This is install ACTIVATOR."
echo

if [ -z "$ROULETTE" ]; then
	echo
	echo "Error including common.config. Setup will now exit. [Press ENTER to Exit.]"
	read
	exit 2 
fi

mkdir -p $ROULETTE/terminal_home/log
LOG=$ROULETTE/terminal_home/log/activator.log
echo `date`" ACTIVATOR start" > $LOG

TestIPAndShowConfigIfNot()
{
        #nekateri sistemi rabijo dodatni ip naslov, prikazemo konfiguracijo uporabniku, da izbere karto
        ping -c 1 -t 5  10.5.10.254 1>>$LOG 2>>$LOG
        if [ "0" != $? ]; then
                echo "Warning"
                echo "Warning: NOT A VALID IP ADDRESS CONFIGURED. PLEASE MAKE SURE AT LEAST ONE ADAPTER HAS IP 10.5.10.254"
                echo "Warning"
                notify-send "Please select a network card for system.     It will be assigned IP=10.5.10.254"
		sleep 2
                sudo -u user sudo gedit /etc/network/interfaces
		service network-manager restart
#                service networking restart
#netplan
#               sudo -u user sudo gedit /etc/netplan/01-netcfg.yaml
#               sudo neplan apply

                ping -c 1 -t 5  10.5.10.254 1>>$LOG 2>>$LOG
                if [ "0" != $? ]; then
                        notify-send "Network settings error!!!! Please restart.."
			sleep 2
                        return 1
                fi
        fi;
return 0
}



#START COLLECTING DATA FROM THE USER, NO changes will be made, until we collect all data!

COMMANDS=()
COMMANDS+=("killall -s9 topscreen >> $LOG")
COMMANDS+=("killall -s9 igplatform >> $LOG")
COMMANDS+=("chroot $FC5 service crond stop >> $LOG")
COMMANDS+=("chroot $FC5 service roulette kill >> $LOG")
COMMANDS+=("killall -s9 roulettesound >> $LOG")
COMMANDS+=("killall -s9 roulettemaster >> $LOG")

clear
echo 
echo "------------------GAMING MACHINE ACTIVATOR--------------------"

ping -c 1 www.google.com 1>/dev/null 2>/dev/null
while [ $? -ne 0 ]; do
#if [ $? -ne 0  ]; then
	echo "ERROR: Activator can not continue without a working internet connection."
	echo "SOLVER: Provide a stable internet connnection, retrying..."
	echo
#	exit 1
#fi
	sleep 3
	ping -c 1 www.google.com 1>/dev/null 2>/dev/null
done
echo "Internet connection is UP and google is reachable."


#Read Gaming Machine Serial Number and other activation information
echo
echo -n "Enter Gaming Machine Serial Number["`hostname`"]:"
read GM_SN
[[ -z $GM_SN ]] && GM_SN=`hostname` #default
GM_SN=${GM_SN^^} #only UPPERCASE letters are allowed
echo "Gaming Machine Serial Number: "$GM_SN

echo
echo -n "Enter Gaming Machine Location: "
read GM_LOCATION
[[ -z $GM_LOCATION ]] && GM_LOCATION="" #default
echo "Location: "$GM_LOCATION 

echo
echo -n "Enter Gaming Machine Legal Owner: "
read GM_OWNER
[[ -z $GM_OWNER ]] && GM_OWNER="" #default
echo "Legal Owner: "$GM_OWNER

echo
echo -n "Enter Gaming Machine Owner Email: "
read GM_OWNER_EMAIL
[[ -z $GM_OWNER_EMAIL ]] && GM_OWNER_EMAIL="" #default
echo "Owner email: "$GM_OWNER_EMAIL

echo
echo -n "Import default Database scripts(say 'no' to keep all from RocetCloud data)?[YES,no]?"
read ans
[[ -z $ans ]] && ans="yes" && echo $ans #default
if [ $ans == "yes" ] || [ $ans == "YES" ]; then
        COMMANDS+=("cd $ROULETTE/initDB")
	COMMANDS+=("./load_db_defaults.sh >> $LOG")
	COMMANDS+=("cd $ROULETTE")
fi

if [ -z $TERMINAL_FLAVOUR ]; then
        echo
        echo -n "Enter TERMINAL FLAVOUR[GAMEART||IMAXA||AIK||BOSS||AGTPLUS||EBX]:"
        read TERMINAL_FLAVOUR
        TERMINAL_FLAVOUR=${TERMINAL_FLAVOUR^^} #uppercase
        [[ -z $TERMINAL_FLAVOUR ]] && TERMINAL_FLAVOUR="GAMEART" #default
        echo $TERMINAL_FLAVOUR
fi
case $TERMINAL_FLAVOUR in
	GAMEART)
		LICENSED_TO="GameART, Slovenia"
;;
	IMAXA)
		LICENSED_TO="Imaxa Gaming, Slovenia"
;;
	AIK)
		LICENSED_TO="Slomatic d.o.o., Slovenia (aik)"
;;
	BOSS)
		LICENSED_TO="BOSS Gaming, Latino America"
;;
	AGTPLUS)
		LICENSED_TO="Enigma d.o.o., Slovenia"
;;
	EBX)
		LICENSED_TO="Enigma d.o.o., Slovenia"
;;
	*)
		./ultra_fast_reboot.sh
esac
echo
echo "Software license will be issued to: "$LICENSED_TO

echo
echo "Select JURISDICTION preset."
echo "Available presets:"
sel=1
for f in `ls $ROULETTE/initDB/jurisdictional/*.sh`; do
	echo "   "$sel". "$(basename $f |cut -d. -f1)
	let "sel++"
done
echo
echo -n "Enter jurisdictional preset number(press 'Enter' to keep all from RocketCloud data):"
read ans
[[ -z $ans ]] && ans="0" && echo "Not loading JURISDICTIONAL preset." #default
[[ $ans -ge $sel ]] && ans="0" && echo "Not loading JURISDICTIONAL preset" #invalid entry
if [ $ans -ne 0 ]; then
	sel=1 #pononvo for-amo, da izberemo filename iz stevilke
	for f in `ls $ROULETTE/initDB/jurisdictional/*.sh`; do
		if [ $sel -eq $ans ]; then
		        COMMANDS+=("cd $ROULETTE/initDB/jurisdictional")
			COMMANDS+=("$f >> $LOG")
			COMMANDS+=("cd $ROULETTE")
			echo $(basename $f |cut -d. -f1)
		fi
		let "sel++"
	done
fi

echo
echo "Install AYNDESK[YES,no]?"
read ans
[[ -z $ans ]] && ans="yes" && echo $ans #default
if [ $ans == "yes" ] || [ $ans == "YES" ]; then
	notify-send "When Anydesk window appears, please configure UNATTENDED ACCESS and choose a PASSWORD.";
        COMMANDS+=("cd /home/user/Documents")
	COMMANDS+=("./install_Anydesk.sh >> $LOG")
	COMMANDS+=("cd $ROULETTE")

	COMMANDS+=("./restartAnydesk.sh restore_or_save >> $LOG")
fi

#ali naredimo DBRepairLevel?
echo
echo -n "Restore default Database[YES,no]?"
read REPAIR_DB_L3
[[ -z $REPAIR_DB_L3 ]] && REPAIR_DB_L3="yes" && echo $REPAIR_DB_L3 #default




#open DISPLAY_SETTINGS, this does not work if run from root!! FIXME!
#COMMANDS+=("sudo -H -u user /usr/bin/gnome-control-center display");
notify-send "Please remember to fix monitor positions. Upper monitor on LEFT side, Bottom monitor on RIGHT side AND Bottom monitor as PRIMARY!!";

echo
echo "OK, we have all information. Start patching system[YES,no]?"
read ans
[[ -z $ans ]] && ans="yes" #default
if [ $ans != "yes" ] && [ $ans != "YES" ]; then
	echo
	echo "User CANCELED."
	echo
	echo "Restart Activator[yes,NO]?"
	read ans
	[[ -z $ans ]] && ans="no" #default
	if [ $ans == "yes" ] || [ $ans == "YES" ]; then
		/bin/bash -c "cd $ROULETTE; $0" && exit $?
	fi
	echo "Please restart GM to finish activation."
	exit 2
fi
echo
echo ""
echo
###########################################################################################################################################
###########################################################################################################################################
###########################################################################################################################################

#PATCH-es
/bin/cp -R $ROULETTE/pack_install/* /
$ROULETTE/OneAmazingScript.sh /etc/network/interfaces /etc/default/isc-dhcp-server /etc/ufw/before.rules
#ze OneAmazingScript naredi network restart!

#check ip 10.5.10.254 and internet connection
TestIPAndShowConfigIfNot
if [ $? -ne 0 ]; then
	echo "ERROR: Activator can not continue without at least one adapter having IP=10.5.10.254"
	exit 3
fi

echo
echo  "We will need 2 minutes ;)"
######################################################
#WE have all data about the system, now start patching
echo "Patching installation for $PRODUCT_NAME"
notify-send "Patching installation for $PRODUCT_NAME. Will restart when done...."

#pozenemo izdelavo terminal_home paketa
if [ -x $ROULETTE/packages/reset_terminal_home.sh ]; then
        $ROULETTE/packages/reset_terminal_home.sh
fi


#START GAMES INSTALLER, so we download while patching...
if [ -x $ROULETTE/packages/Games/games-installer.sh ]; then
	GAMES_INSTALLER=$ROULETTE/packages/Games/games-installer.sh
	if [ -x $GAMES_INSTALLER ]; then
		lxterminal --command="$GAMES_INSTALLER no_reboot" --title="$PRODUCT_NAME GAMES INSTALLER - download games while we patch the system" --geometry=170x70 1>/dev/null 2>/dev/null &
		sleep 0.5
		GAMES_INSTALLER_PID=`ps -A|grep games-installer|cut -d" " -f 2-2`
		echo "###We will wait for INSTALLER PID=$GAMES_INSTALLER_PID"
	fi
else
	GAMES_INSTALLER_PID=-1
fi


#change hostname to GM Serial Number
hostn=$(cat /etc/hostname); 
hostname $GM_SN; 
sed -i "s/$hostn/$GM_SN/g" /etc/hosts;
sed -i "s/$hostn/$GM_SN/g" /etc/hostname; 
echo "$GM_SN" > $FC5/RouletteMaster/ROULETTE_NAME;

if [ $REPAIR_DB_L3 == "yes" ] || [ $REPAIR_DB_L3 == "YES" ]; then
#	$IGP/symmetricDS/tools/symmetricDSServiceDisable.sh >> $LOG
	chroot $FC5 /RouletteMaster/EMPTY_DATABASE/repair_db_level3.sh >> $LOG
fi

#Imamo NODE_ID=$GMS in nastavljen novi HOSTNAME; takoj zazenemo symmetricDS, da se registrira
echo "Starting symmetricDS serivce for node: $GM_SN"
$IGP/symmetricDS/tools/symmetricDSServiceEnable.sh $GM_SN
#pocakamo registracijo
$ROULETTE/symmetricDS/tools/checkSymTablesInDB.sh
res=$?
while [ $res -eq 0 ]; do
	echo "Waiting for symmetricDS registration... Please make sure you have a working internet connection!"
	$ROULETTE/symmetricDS/bin/sym_service start
	sleep 5
	$ROULETTE/symmetricDS/tools/checkSymTablesInDB.sh
	res=$?
done

#to je potrebno pognati iz RocketCloud, glede na situacijo!
#echo "Starting symmetricDS REVERSE LOAD...."
#sleep 5
#nohup chroot $FC5 /RouletteMaster/symmetric_init_load_reload.sh REVERSELOAD >/dev/null &
#sleep 5
#if [ $? -ne 0 ]; then
#fi ??


#izkjlucimno update notifier
gsettings set com.ubuntu.update-notifier no-show-notifications true 2>>$LOG 1>>$LOG
sudo -H -u user dconf write "/org/compiz/profiles/unity/plugins/unityshell/launcher-hide-mode" 1  2>>$LOG 1>>$LOG
#disable automatic updates
systemctl disable apt-daily.service apt-daily-upgrade.service
systemctl disable apt-daily.timer apt-daily-upgrade.timer

#ob prvem zagonu po instalaciji moramo ponovno izracunati kjluce za sshd
dpkg-reconfigure openssh-server
echo -n Updating grub...
update-grub 2>>$LOG 1>>$LOG
echo OK

#wine-u nastavimo memorysize - potrebno za GameART igre
#echo
#echo "Settig videomemorysize=1024 for WINE..."
#sudo -H -u user winetricks videomemorysize=1024 1>>$LOG 2>>$LOG

#ponekdaj se je zgodilo da je ostall ufw ugasnjen
echo
echo "Configuring Uncomplicated FireWall..."
ufw allow 10256
ufw allow 5555
ufw enable

#menjamo loading splash logo!
#je ze skopiran iz mape pack_install
#cp /home/ROULETTE/terminal/graphics/GAMEART/loading-splash.png /usr/share/plymouth/ubuntu-logo.png
#cp /home/ROULETTE/terminal/graphics/GAMEART/loading-splash.png /usr/share/plymouth/themes/ubuntu-logo/ubuntu-logo16.png
#cp /home/ROULETTE/terminal/graphics/GAMEART/loading-splash.png /usr/share/plymouth/themes/ubuntu-logo/ubuntu-logo.png
#/RouletteMaster/host_execute.sh sudo update-alternatives --config default.plymouth
update-initramfs -u 2>>$LOG 1>>$LOG


#SYMMMETRICDS is running
#START ADDING data into database

#execute all commands from previous statements
echo "Running commands and SQL-s...."
for cmd in "${COMMANDS[@]}"
do
	echo "Running $cmd"
	$cmd
done

echo "select RESULT from SET_PARAM('GLOBAL','ACTIVATOR', 'ROULETTE_NAME', 'Gaming Machine Name','Name of this machine. It will be used for identification.', 11, NULL, '$GM_SN')" | $ROULETTE/sqlexec.sh
echo "select RESULT from SET_PARAM('GLOBAL','ACTIVATOR', 'SERIAL_NUMBER', 'Serial Number','Serial number used for SAS and online systems.', 11, NULL, '$GM_SN')" | $ROULETTE/sqlexec.sh
echo "select RESULT from SET_PARAM('GLOBAL','ACTIVATOR', 'MACHINE_LOCATION', 'GM Location','Location, where this Gaming Machine is installed.', 11, NULL, '$GM_LOCATION')" | $ROULETTE/sqlexec.sh
echo "select RESULT from SET_PARAM('GLOBAL','ACTIVATOR', 'MACHINE_OWNER', 'GM Owner','Name of the legal owner of this Gaming Machine.', 11, NULL, '$GM_OWNER')" | $ROULETTE/sqlexec.sh
echo "select RESULT from SET_PARAM('GLOBAL','ACTIVATOR', 'OWNER_EMAIL', 'Owner email','Email address of this Gaming Machine owner.', 11, NULL, '$GM_OWNER_EMAIL')" | $ROULETTE/sqlexec.sh
echo "select RESULT from SET_PARAM('GLOBAL','ACTIVATOR', 'LICENSED_TO', 'Licensed To','The Company name this copy of the software was issued to.', 11, NULL, '$LICENSED_TO')" | $ROULETTE/sqlexec.sh
echo "select RESULT from SET_PARAM('GLOBAL','ACTIVATOR', 'TERMINAL_FLAVOUR', 'Terminal Flavour','GAMEART||IMAXA||AIK||BOSS||AGTPLUS||EBX', 11, NULL, '$TERMINAL_FLAVOUR')" | $ROULETTE/sqlexec.sh
echo "select RESULT from SET_PARAM('GLOBAL','ACTIVATOR', 'TERMINALS_LICENSED', 'Terminals Licensed','', 11, 8, '')" | $ROULETTE/sqlexec.sh
echo "select * from set_param('GLOBAL', 'ACTIVATOR', 'PRODUCT_NAME', '','', 11, 0, '$PRODUCT_NAME')" |$ROULETTE/sqlexec.sh



#do not enter here anymore - to bi moralo iti v INIT in tam preverjati result te skripte - jutri je kamion.
echo "roulettefirstboot has already been run" > $FIRSTBOOTFILE
echo "delete this file to run it again." >> $FIRSTBOOTFILE


#wait for games installer to complete
while [ -e /proc/$GAMES_INSTALLER_PID ]
do
	echo "###Waiting for GamesInstaller to finish copying packages...."
	sleep 3
done
echo "###PID=$GAMES_INSTALLER_PID has completed."

#so igrice z .update.., ne moremo startati aplikacije, nujen je reboot!
#echo
#echo -n "Activator is complete. Start application?[YES,no]:"
#read ans
#[[ -z $ans ]] && ans="yes" && echo $ans #default
#if [ $ans == "yes" ] || [ $ans == "YES" ]; then
#        $ROULETTE/INIT.SH
#fi

echo "Done. Press Enter..."
read ans #ignore

echo
echo -n "Installer is complete. We have to reboot. Reboot now?[YES,no]: "
read ans
[[ -z $ans ]] && ans="yes" && echo $ans #default
if [ $ans == "yes" ] || [ $ans == "YES" ]; then
        /home/IGP/ultra_fast_reboot.sh
	sleep 1
	init 6
fi


exit 0

 

