#!/bin/bash

INSTALLOPTIONALDEPS=0
ADDCRONJOBS=0
RUNINSTALL=0

DEPENDENCIES="xvfb mono-runtime rsync libxml2-utils"
OPTDEPENDENCIES="sendemail sendxmpp"

if [ -n "$(command -v apt-get)" ]; then
	ISDEBIAN=1
else
	ISDEBIAN=0
fi

if [ $(uname -m) == 'x86_64' ]; then
	IS64BIT=1
else
	IS64BIT=0
fi

if [[ $IS64BIT == 1 ]]; then
	DEPENDENCIES="$DEPENDENCIES lib32gcc1 wine:i386"
else
	DEPENDENCIES="$DEPENDENCIES wine"
fi

showHelp() {
	echo "Usage: ./bootstrap.sh [-h] [-o] [-c] -i"
	echo "Parameters:"
	echo "  -h   Print this help screen and exit"
	echo "  -o   Install optional dependencies ($OPTDEPENDENCIES)"
	echo "  -c   Add cron jobs for save backups and memory checking"
	echo "  -i   Required to actually start the installation"
}

intro() {
	echo
	echo "7DtD Linux dedicated server bootstrapper"
	echo
	echo "This will install a 7DtD server according to the information"
	echo "given on:"
	echo "   http://7daystodie.gamepedia.com/Linux_Server"
	echo
	read -p "Press enter to continue"
	echo -e "\n=============================================================\n\n"
}

nonDebianWarning() {
	if [[ $ISDEBIAN == 0 ]]; then
		echo "NOTE: It seems like this system is not based on Debian."
		echo "Although installation of the scripts and SteamCMD/7dtd"
		echo "will work the installed management scripts will probably"
		echo "*NOT* work out of the box and installation of dependencies"
		echo "will fail too."
		echo "Do you want to continue anyway?"
		select yn in "Yes" "No"; do
			case $yn in
				Yes)
					echo "Continuing..."
					break;;
				No)
					echo "Aborting."
					exit 0
					;;
			esac
		done
		echo -e "\n=============================================================\n\n"
	fi
}

installAptDeps() {
	echo -e "Installing dependencies\n"
	if [[ $IS64BIT == 1 ]]; then
		dpkg --add-architecture i386
	fi
	apt-get update
	apt-get install $DEPENDENCIES
	echo -e "\n=============================================================\n\n"
}

installOptionalDeps() {
	echo -e "Installing optional dependencies\n"
	apt-get install $OPTDEPENDENCIES
	echo -e "\n=============================================================\n\n"
}

setupUser() {
	echo -e "Setting up user and group \"sdtd\"\n"
	useradd -d /home/sdtd -m -r -s /bin/bash -U sdtd
	echo -e "\n=============================================================\n\n"
}

installManagementScripts() {
	echo -e "Downloading and installing management scripts\n"
	wget -nv http://illy.bz/fi/7dtd/management_scripts.tar.gz -O /tmp/management_scripts.tar.gz
	tar -xzf /tmp/management_scripts.tar.gz --no-same-owner --owner=root --group=root -C /
	chmod go-rwx /etc/7dtd.conf
	chmod +x /etc/init.d/7dtd.sh
	chmod +x /usr/local/bin/7dtd-*
	if [[ $ISDEBIAN == 1 ]]; then
		update-rc.d 7dtd.sh defaults
	fi
	echo -e "\n=============================================================\n\n"
}

setSteamLoginData() {
	echo -e "Steam account data\n"
	echo "Please enter your Steam login data for SteamCMD to get the 7dtd-server files:"
	read -p "Steam username: " username
	read -s -p "Steam password: " password
	sed -i "s/export STEAM_USER=/export STEAM_USER=$username/" /etc/7dtd.conf
	sed -i "s/export STEAM_PASS=/export STEAM_PASS=$password/" /etc/7dtd.conf
	echo -e "\n=============================================================\n\n"
}

installSteamCmdAndSDTD() {
	echo -e "Installing SteamCMD and 7DtD\n"
	7dtd-update.sh
	cp -p /home/sdtd/7dtd/serverconfig.xml /home/sdtd/
	echo -e "\n=============================================================\n\n"
}

setupServerConfig() {
	echo -e "Setting up basic 7DtD server config\n"

	until [[ $public == "y" || $public == "n" ]]; do
		read -p "Should the server be public [yn]? " public
	done
	if [[ "$public" == "y" ]]; then public=true; else public=false; fi
	echo

	read -p "Server name: " servername
	echo
	read -p "Server password (empty for none): " serverpassword
	echo

	echo "Select world to play on:"
	select worldname in "Navezgane" "MP Forest Horde" "MP Forest Skirmish" "MP Wasteland Horde" "MP Wasteland Skirmish" "MP Wasteland War"; do
		if [[ -n $worldname ]]; then
			break
		fi
	done
	echo

	echo "Select game mode:"
	select gamemode in "GameModeSurvival" "GameModeZombieHorde" "GameModeDeathmatch"; do
		if [[ -n $gamemode ]]; then
			break
		fi
	done
	echo

	read -p "Game name: " gamename
	echo
	read -p "Difficulty (0-4): " difficulty
	echo

	sed -i "s/name=\"ServerIsPublic\".*value=\"[^\"]*\"/name=\"ServerIsPublic\" value=\"$public\"/" /home/sdtd/serverconfig.xml
	sed -i "s/name=\"ServerName\".*value=\"[^\"]*\"/name=\"ServerName\" value=\"$servername\"/" /home/sdtd/serverconfig.xml
	sed -i "s/name=\"ServerPassword\".*value=\"[^\"]*\"/name=\"ServerPassword\" value=\"$serverpassword\"/" /home/sdtd/serverconfig.xml
	sed -i "s/name=\"GameWorld\".*value=\"[^\"]*\"/name=\"GameWorld\" value=\"$worldname\"/" /home/sdtd/serverconfig.xml
	sed -i "s/name=\"GameName\".*value=\"[^\"]*\"/name=\"GameName\" value=\"$gamename\"/" /home/sdtd/serverconfig.xml
	sed -i "s/name=\"GameDifficulty\".*value=\"[^\"]*\"/name=\"GameDifficulty\" value=\"$difficulty\"/" /home/sdtd/serverconfig.xml
	sed -i "s/name=\"GameMode\".*value=\"[^\"]*\"/name=\"GameMode\" value=\"$gamemode\"/" /home/sdtd/serverconfig.xml
	sed -i "s/name=\"TelnetPort\".*value=\"[^\"]*\"/name=\"TelnetPort\" value=\"25003\"/" /home/sdtd/serverconfig.xml

	echo -e "\n=============================================================\n\n"
}

addCronJobs() {
	echo -e "Adding cron jobs\n"

	echo -e "By default a backup of the save folder will be created once"
	echo -e "  per hour. This can be changed in /etc/cron.d/7dtd-backup."
	echo -e "Memory monitor will be run every five minutes by default."
	echo -e "  This can be changed in /etc/cron.d/7dtd-check_mem."

	echo "0 *     * * *   root    /usr/local/bin/7dtd-backup.sh" > /etc/cron.d/7dtd-backup
	echo "*/5 *   * * *   root    /usr/local/bin/7dtd-check_mem.sh" > /etc/cron.d/7dtd-check_mem

	echo -e "\nNOTE: Do not forget to edit /etc/7dtd.conf to match\nyour notification needs!"
	echo -e "\n=============================================================\n\n"
}

finish() {
	echo -e "\n ALL DONE\n"
	echo -e "You should now be able to start your 7dtd server by running\n"
	echo -e "      7dtd-start.sh\n"
	echo
	echo -e "For further configuration options check:"
	echo -e "  /etc/7dtd.conf"
	echo -e "  /home/sdtd/serverconfig.xml"
	echo
	echo -e "For feedback, suggestions, problems please visit the forum:"
	echo -e "  http://7daystodie.com/forums/showthread.php?2188"
	echo
}

main() {
	intro
	nonDebianWarning

	if [[ $ISDEBIAN == 1 ]]; then
		installAptDeps
		if [[ $INSTALLOPTIONALDEPS == 1 ]]; then
			installOptionalDeps
			echo
		fi
	fi
	setupUser
	installManagementScripts
	setSteamLoginData
	installSteamCmdAndSDTD
	if [[ $ADDCRONJOBS == 1 ]]; then
		addCronJobs
	fi
	setupServerConfig
	finish
}

if [[ -z $1 ]]; then
	showHelp
	exit 0
fi
while getopts "hcoi" opt; do
	case "$opt" in
		h)
			showHelp
			exit 0
			;;
		c)
			ADDCRONJOBS=1
			;;
		o)
			INSTALLOPTIONALDEPS=1
			;;
		i)
			RUNINSTALL=1
			;;
	esac
done
if [[ $RUNINSTALL == 1 ]]; then
	main
fi

