#!/bin/bash

# Check if Root
if [[ $EUID -ne 0 ]]; then
	# Log In as Root
	echo "Logging in as root ..."
	su -c '. install.sh'
else
	# Basic Info
	read -p "Your Username: " USER
	PREFIX="/home/${USER}/armagetronad"
	
	# Make Sure USER Exists
	if [[ ! -d "/home/${USER}" ]]; then
		echo "Fatal Error: User \"${USER}\" Doesn't Exist"
		exit 1
	fi
	
	# Go to Home Dir
	cd /home/$USER
	
	# Install Required Packages
	apt-get update
	apt-get -y --ignore-missing install bzr build-essential automake libboost-dev libxml2-dev libsdl-image1.2-dev libsdl-mixer1.2-dev libftgl-dev libglew-dev bison pkg-config autoconf autotools-dev libprotobuf-dev libtool curl make g++ unzip sudo php perl screen
	
	# Check for protoc
	if [ $(which protoc | wc -l) -lt 1 ]; then
		# Download Protobuf
		git clone https://github.com/google/protobuf.git
		
		# Enter Dir
		cd protobuf
		
		# Build & Install
		git submodule update --init --recursive
		./autogen.sh
		make
		make install
	fi
	
	# Check for ZThread
	if [[ ! -d "/usr/include/zthread" ]]; then
		# Download & Extract
		wget http://resource.armagetronad.net/resource/ZThread-2.3.2.tar.gz
		tar xvzf ZThread-2.3.2.tar.gz
		
		# Enter Dir
		cd ZThread-2.3.2
		
		# Fix Config File
		CONFIG=$(cat configure | sed 's/\[:space:\]/[[:space:]]/g')
		echo "${CONFIG}" > configure
		
		# Configure ZThread
		./configure CXXFLAGS="-fpermissive" --prefix=/usr/
		
		# Build & Install
		make
		make install
	fi
	
	# Download the Server
	sudo -u $USER bzr branch lp:~armagetronad-ap/armagetronad/0.2.9-armagetronad-sty+ct+ap
	
	# Enter Server BZR Dir
	cd 0.2.9-armagetronad-sty+ct+ap
	
	# Create Destination Dir
	if [[ ! -d "${PREFIX}" ]]; then
		sudo -u $USER mkdir $PREFIX
	fi
	
	# Configure the Server
	sudo -u $USER ./bootstrap.sh
	sudo -u $USER ./configure --prefix=$PREFIX --disable-glout --enable-authentication --with-zthread --disable-sysinstall --disable-useradd --disable-etc --disable-desktop --disable-uninstall
	
	# Build & Install
	sudo -u $USER make
	sudo -u $USER make install
	
	# Mod Permission of Bin to 755 (rwxr-xr-x)
	chmod 755 $PREFIX/bin
	
	# Remove Leftovers
	rm -Rv /home/$USER/0.2.9-armagetronad-sty+ct+ap
	rm -Rv /home/$USER/ZThread-2.3.2
fi
