#!/bin/bash

SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
OUTPUT_DIR="$2"
CFG_FILE="$3"
DEFAULT_CFG_FILE=UnrealTournament.ini


function install() {
	cp $SCRIPT_DIR/Help		$OUTPUT_DIR/Help		-R
	cp $SCRIPT_DIR/System	$OUTPUT_DIR/System		-R
	cp $SCRIPT_DIR/Textures $OUTPUT_DIR/Textures	-R
	
	echo install ok
}

function enable() {
	SSBUFile=$(find $OUTPUT_DIR/System -type f -iname "SmartSB*.u" ! -name "SmartSBStats.u" -exec basename {} \;)
	SSBBaseName="${SSBUFile%.*}"
	
	# Warning: ugly hack with sed to allow multiple key instances
	crudini --set $OUTPUT_DIR/System/$CFG_FILE 'Engine.GameEngine' _ServerPackages $SSBBaseName
	sed -i 's/_ServerPackages/ServerPackages/g' 	$OUTPUT_DIR/System/$CFG_FILE
	
	crudini --set $OUTPUT_DIR/System/$CFG_FILE 'Engine.GameEngine' _ServerPackages SmartSBStats
	sed -i 's/_ServerPackages/ServerPackages/g' 	$OUTPUT_DIR/System/$CFG_FILE
	
	crudini --set $OUTPUT_DIR/System/$CFG_FILE 'Engine.GameEngine' _ServerActors $SSBBaseName.SmartSBServerActor
	sed -i 's/_ServerActors/ServerActors/g' 	$OUTPUT_DIR/System/$CFG_FILE
	
	echo enable ok
}

function disable() {
	SSBUFile=$(find $OUTPUT_DIR/System -type f -iname "SmartSB*.u" ! -name "SmartSBStats.u" -exec basename {} \;)
	SSBBaseName="${SSBUFile%.*}"
	
	sed -i "/ServerPackages[[:space:]]*=[[:space:]]*$SSBBaseName/d" $OUTPUT_DIR/System/$CFG_FILE
	sed -i "/ServerPackages[[:space:]]*=[[:space:]]*SmartSBStats/d" $OUTPUT_DIR/System/$CFG_FILE
	sed -i "/ServerActors[[:space:]]*=[[:space:]]*$SSBBaseName.SmartSBServerActor/d" $OUTPUT_DIR/System/$CFG_FILE
	
	echo disable ok
}

function show_help() {
	echo
	echo "Usage: $0 { install | enable | disable } <UT99_INSTALL_DIR> [<UT99_CONFIG_FILE>]"
	echo
}

function check_cfg_file() {
	if [ -z ${CFG_FILE} ]
	then
		echo "CFG_FILE is unset, setting it to $DEFAULT_CFG_FILE"
		CFG_FILE=$DEFAULT_CFG_FILE
	else
		echo "CFG_FILE is set to '$CFG_FILE'"
	fi

	if [ ! -f $OUTPUT_DIR/System/$CFG_FILE ]
	then
		echo "$OUTPUT_DIR/System/$CFG_FILE does not exist"
		show_help
		exit 9999 # die with error code 9999
	fi
}

function check_game_dir() {
	### Check if a directory does not exist ###
	if [ ! -d $OUTPUT_DIR ]
	then
		echo "incorrect <UT99_INSTALL_DIR>"
		show_help
		exit 9999 # die with error code 9999
	fi
}

case "$1" in
	'install')
			check_game_dir
			install
			;;
	'enable')
			check_game_dir
			check_cfg_file
			disable
			enable
			;;
	'disable')
			check_game_dir
			check_cfg_file
			disable
			;;
	*)
			show_help
			exit 1
			;;
esac

exit 0