# This script installs Xtribe. It can be launched with three parameters:
# - install: install Xtribe from scratch 
# - install_games: 
# - install_managers:
# - update: update Xtribe, from the official repository
# - repair: reset and setup again all Xtribe setting, in order to correct or modify them.
# - uninstall: uninstall Xtribe_

#!/bin/sh

op_line="--------------------------------------\n"
close_line="\n--------------------------------------"

# These three variables maintain the state of process (it's installing, updating, reparing or whatever)
repair="0"
install="0"
update="0"
uninstall="0"
error_failed_setup="0"
db_name='xtribe'
db_usr='xtribe'
db_urs_pwd='xtribe123'

db_name_games=(cityrace eaic elise quorum)
db_user_games=(cityrace eaic elise quorum)
db_password_games=(alinasirbu misuroeaic2 perelise alinasirbu)
db_host_games=(localhost localhost localhost %);
limit_array=$((${#db_name_games[@]}-1))

db_host="localhost";

################################ GENERAL FUNCTIONS

setup_failed(){
	echo "$op_line Setup failed. $1 $close_line" ; 
	error_failed_setup="1"
	if [ "$install" = "1" ]; then
		echo -n "System needs to be cleaned up due to a failed installation. Are you sure you want to uninstall xtribe? ATTENTION: This will delete permanently xtribe files and database. (y/n) "
		read yesno < /dev/tty
		while [ "$yesno" != "y" ] && [ "$yesno" != "n" ]; do
			echo -n "--- Please reply with a single characther: 'y' or 'n': "
			read yesno < /dev/tty
		done
		if [ "$yesno" = "y" ]; then
			uninstall_xtribe	
		fi
	fi
	exit 1;
}

exit_cause(){
	echo "$op_line $1 $close_line" ; 
	exit 1;
}

setup_permission_on_all_files(){
	cd /var/www
	sudo chown -R www-data:www-data xtribe.eu 
}

reboot_system(){
	echo -n "System needs to be restarted. Do you want to restart? (y/n) "
	read yesno < /dev/tty
	while [ "$yesno" != "y" ] && [ "$yesno" != "n" ]; do
		echo -n "--- Please reply with a single characther: 'y' or 'n': "
		read yesno < /dev/tty
	done
	if [ "$yesno" = "y" ]; then
		reboot	
	fi
}

check_xtribe_is_installed_or_exit(){
	cd /var/www/xtribe.eu > /dev/null 2>/dev/null	
	if [ "$?" != "0" ]; then 
		exit_cause "Setup failed. No Xtribe installation detected."	
	fi
}

check_games_are_installed_or_exit(){
	cd /var/www/xtribe.eu/files > /dev/null 2>/dev/null	
	if [ "$?" != "0" ]; then 
		exit_cause "Setup failed. You must install games before installing managers."	
	fi
}

check_arg_dir_is_empty_or_exit(){
	if [ "$(ls -A $1)" ]; then 
		exit_cause "Setup failed. Xtribe $1 directory is not empty."	
	fi
}

store_xtribe_install_mode(){
	cd /var/www/xtribe.eu
	echo "$local_or_web" > "install.txt"
}

################################ CHECK EXTERNAL SOFTWARE AVAILABILITY 
check_nodejs_is_installed(){
	echo "--- Checking Node.js..."	
	nodejs --version > /dev/null 2>/dev/null
	if [ "$?" != "0" ]; then
		setup_failed "Node.js not found. Please run: sudo apt-get install nodejs."
	else
		echo "Node.js correctly installed."	
	fi
}

check_phyton_is_installed(){
	echo "--- Checking Python..."	
	python --version > /dev/null 2>/dev/null
	if [ "$?" != "0" ]; then
		setup_failed "Python not found. Please run: sudo apt-get install python-pip."
	else
		echo "Python correctly installed."	
	fi
}

check_sqlite3_is_installed(){
	echo "--- Checking Sqlite3..."	
	sqlite3 --version > /dev/null 2>/dev/null
	if [ "$?" != "0" ]; then
		setup_failed "Sqlite3 not found. Please run: sudo apt-get install sqlite3 libsqlite3-dev."
	else
		echo "Sqlite3 correctly installed."	
	fi
}

check_npm_is_installed(){
	echo "--- Checking Npm..."	
	npm --version > /dev/null 2>/dev/null
	if [ "$?" != "0" ]; then
		setup_failed "Npm not found. Please run: sudo apt-get install npm."
	else
		echo "Npm correctly installed."	
	fi
}

check_php5_is_installed(){
	echo "--- Checking Php5..."	
	php5 --version > /dev/null 2>/dev/null
	if [ "$?" != "0" ]; then
		setup_failed "Php5 not found. Please run: sudo apt-get install php5."
	else
		echo "Php5 correctly installed."	
	fi
}

check_mysql_is_installed(){
	echo "--- Checking Mysql..."	
	mysql --version > /dev/null 2>/dev/null
	if [ "$?" != "0" ]; then
		setup_failed "Mysql not found. Please run: sudo apt-get install mysql."
	else
		echo "Mysql correctly installed."	
	fi
}

check_haproxy_is_installed(){
	echo "--- Checking HaProxy..."	
	haproxy --version > /dev/null 2>/dev/null
	if [ "$?" = "127" ]; then
		setup_failed "HaProxy not found. Please run: sudo apt-get install haproxy."
	else
		echo "HaProxy correctly installed."	
	fi
}

check_redis_is_installed(){
	echo "--- Checking Redis Server..."	
	redis-cli --version > /dev/null 2>/dev/null
	if [ "$?" != "0" ]; then
		setup_failed "Redis Server not found. Please run: sudo apt-get install redis-server."
	else
		echo "Redis Server correctly installed."	
	fi
}

check_drush_is_installed(){
	echo "--- Checking Drush..."	
	drush --version > /dev/null 2>/dev/null
	if [ "$?" != "0" ]; then
		setup_failed "Drush not found. Please install it. Please run: sudo apt-get install drush."
	else
		echo "Drush correctly installed."	
	fi
}

check_upstart_is_installed(){
	echo "--- Checking Upstart..."	
	initctl --version > /dev/null 2>/dev/null
	if [ "$?" != "0" ]; then
		setup_failed "Upstart not found. Please install it."
	else
		echo "Upstart correctly installed."	
	fi
}

check_apache2_is_installed(){
	echo "--- Checking Apache2..."	
	which apache2 > /dev/null 2>/dev/null
	if [ "$?" != "0" ]; then
		setup_failed "Apache2 not found. Please install it."
	else
		echo "Apache2 correctly installed."	
	fi
}

check_git_is_installed(){
	echo "--- Checking Git..."	
	git --version > /dev/null 2>/dev/null
	if [ "$?" != "0" ]; then
		setup_failed "Git not found. Please install it. Please run: sudo apt-get install git."
	else
		echo "Git correctly installed."	
	fi
}

################################ EXTERNAL SOFTWARE SETUP 

setup_cronjob_backup_db(){
	cd /var/www/xtribe.eu/etsmaintenance/cron_jobs/
	crontab root
}

setup_cronjob_airprobe(){
	cd /var/www/xtribe.eu/etsmaintenance/cron_jobs/
	crontab -u www-data www-data
}

setup_haproxy(){
	echo "--- Setting Haproxy..."
	cd /var/www/xtribe.eu/ets/conf/
	cp ets-haproxy.conf /etc/init/
}

setup_redis(){
	echo "--- Setting Redis..."
	cd /var/www/xtribe.eu/ets/conf/
	cp redis-server /etc/init.d/

	# restore db dump
	cp /var/www/xtribe.eu/etsmaintenance/redis/dump.rdb /var/lib/redis/dump.rdb
	chown redis: /var/lib/redis/dump.rdb
}

setup_apache2(){
	echo "--- Setting Apache2..."
	# enabling mod_rewrite
	a2enmod rewrite
	
	# setting virtual host configuration
	echo "--- Setting Apache2 to listen on port 8080..."
	cd /etc/apache2/
	sed -i "s/Listen 80$/Listen 8080/" ports.conf

	cd /var/www/xtribe.eu/ets/conf/
	cp xtribe_apache /etc/apache2/sites-available/xtribe.conf
	cd /etc/apache2/sites-available/
	ln -s xtribe /etc/apache2/sites-enabled/xtribe.conf

	#if [ "$local_or_web" = "l" ]; then
	#	sed -i "s/ServerName.*/ /" xtribe
	#fi
	#if [ "$local_or_web" = "w" ]; then
	#	echo "Please type your server settings."
	#	echo -n "Server name (can be empty): "
	#	read server_name < /dev/tty
	#	if [ "server_name" != "" ]; then
	#		sed -i "s/ServerName.*/ServerName $server_name/" xtribe
	#	else
	#		sed -i "s/ServerName.*/ /" xtribe
	#	fi
	#	echo -n "Your domain ip (ex.142.67.19.2): "
	#	read ip_domain < /dev/tty
		# control if there's yet the association ip-servername in the hosts file. If there is, it does nothing.
		# If there's the ip, the server name it's added. If there's no association it adds it at the beginning.
	#	cd /etc		
	#	grep -e "$ip_domain\s.*$server_name\s" -e "$ip_domain.*$server_name$" hosts > /dev/null 2> /dev/null
	#	if [ "$?" != "0" ]; then
	#		grep -e "$ip_domain\s" hosts > /dev/null 2> /dev/null
	#		if [ "$?" = "0" ]; then	
	#			sed -i "s/$ip_domain/$ip_domain $server_name/" hosts	
	#		else	
	#			sed -i "1s/^/$ip_domain $server_name\n/" hosts
	#		fi
	#	fi
	#fi

	a2ensite xtribe
	a2dissite default
	a2dissite 000-default
	service apache2 restart
}

setup_upstart(){
	echo "--- Setting Upstart..."
	cd /var/www/xtribe.eu/ets/conf/
	cp ets-server.conf /etc/init/
	echo "Please type your Node.js settings."
	echo -n "Node.js bin directory (ex./usr/bin/nodejs): "
	read nodejs_dir < /dev/tty

	cd /etc/init
	sed -i "s,NODE_BIN=.*,NODE_BIN=$nodejs_dir," ets-server.conf

	#Solves a rename problem of newer version of node
	if [ ! -f $nodejs_dir/node ] && [ -f $nodejs_dir/nodejs ]; then
  		ln -s $nodejs_dir/nodejs $nodejs_dir/node
	fi
}

################################ XTRIBE SETUP
setup_repo() {
	cd /var/www
	# if directory exist and i'm not in repairing mode
	if [ -d xtribe.eu ] && [ "$repair" = "0" ]; then
		setup_failed "Directory xtribe.eu already exist."
	else
		echo "--- Creating directory xtribe.eu..."
		mkdir xtribe.eu
		cd xtribe.eu
		echo "--- Initializing git repository..."
		git init									# initialize repo
		echo "--- Adding remote repository..."
		git remote add origin https://xtribe@bitbucket.org/xtribe/xtribe.eu.git 	# add remote repo
	fi
}

update_data_from_repo(){
	cd /var/www/xtribe.eu
	echo "--- Getting data from remote repository..."		
	git pull origin master									# get data from remote repo
	if [ $? = "1" ]; then
		setup_failed "Cannot get data from remote repository."
	fi						
	git add *								
	cd /var/www
	sudo chown -R www-data:www-data xtribe.eu 						# permission for new files
}

setup_games(){
	echo -n "Do you want to install our games? (You must own a password to access our games repository) (y/n) "
	read yesno < /dev/tty
	while [ "$yesno" != "y" ] && [ "$yesno" != "n" ]; do
		echo -n "--- Please reply with a single characther: 'y' or 'n': "
		read yesno < /dev/tty
	done
	if [ "$yesno" = "y" ]; then
		check_xtribe_is_installed_or_exit
		check_arg_dir_is_empty_or_exit /var/www/xtribe.eu/files/
		check_phyton_is_installed
		check_sqlite3_is_installed

		cd /var/www/xtribe.eu
		echo "--- Getting data from games remote repository..."		
		git submodule init files
		git submodule update

		sudo chown -R www-data:www-data files

		cd /var/www/xtribe.eu/files/custom_data_db
		echo "--- Updating Drupal database..."
		mysql -u $db_usr -p$db_urs_pwd $db_name < db_custom_data.sql || setup_failed "Database failed updating."

		echo "--- Creating and populating games databases... (May take a while)"	
		for i in $(seq 0 $limit_array);
		  do
			mysql -u $db_root_usr -p$db_root_urs_pwd -e "use ${db_name_games[i]}"> /dev/null 2>/dev/null
			if [ $? = "0" ]; then
				setup_failed "Database already exists."
			else
				cd /var/www/xtribe.eu
				mysqladmin -u $db_root_usr -p$db_root_urs_pwd create "${db_name_games[i]}" || setup_failed "Could not create database."

				#  creating user to manage db
				if [ "${db_host_games[i]}" != "%" ]; then
					mysql -u $db_root_usr -p$db_root_urs_pwd -e "GRANT ALL PRIVILEGES ON ${db_name_games[i]}.* TO ${db_user_games[i]}@${db_host_games[i]} IDENTIFIED BY '${db_password_games[i]}'"
				else
					mysql -u $db_root_usr -p$db_root_urs_pwd -e "GRANT ALL PRIVILEGES ON ${db_name_games[i]}.* TO ${db_user_games[i]} IDENTIFIED BY '${db_password_games[i]}'"
				fi
				mysql -u $db_root_usr -p$db_root_urs_pwd -e "FLUSH PRIVILEGES"
				cd /var/www/xtribe.eu/files/custom_data_db
				mysql -u $db_root_usr -p$db_root_urs_pwd "${db_name_games[i]}" < "${db_name_games[i]}".sql || setup_failed "Database failed updating."
			fi
	    done	

	    setup_cronjob_airprobe	
	fi
}

setup_managers(){
	echo -n "Do you want to install our games managers? (You must own a password to access our games managers)  (y/n) "
	read yesno < /dev/tty
	while [ "$yesno" != "y" ] && [ "$yesno" != "n" ]; do
		echo -n "--- Please reply with a single characther: 'y' or 'n': "
		read yesno < /dev/tty
	done
	if [ "$yesno" = "y" ]; then
		check_xtribe_is_installed_or_exit
		check_games_are_installed_or_exit
		check_arg_dir_is_empty_or_exit /var/www/xtribe.eu/etsman/

		cd /var/www/xtribe.eu
		echo "--- Getting data from games managers remote repository..."		
		git submodule init etsman
		git submodule update

		sudo chown -R www-data:www-data etsman

		cd /var/www/xtribe.eu/ets/conf/
		cp ets-managers.conf /etc/init/
		cp ets-managers-creastoria.conf /etc/init/
		cp ets-managers-creastoriavs.conf /etc/init/

		# create log file and giving permissions
		echo "--- Creating log file and giving permissions..."
		mkdir -p /var/log/ets/
		touch /var/log/ets/managers.log
		cd /var/log/
		sudo chown -R www-data:www-data ets

		# giving localhost address to managers
		echo "--- Setting games managers address to localhost..."
		mysql -u $db_usr -p$db_urs_pwd $db_name -e "UPDATE field_data_field_mgr_uri SET field_mgr_uri_value = replace(field_mgr_uri_value,'man.xtribe.eu','localhost') WHERE field_mgr_uri_value LIKE '%man.xtribe.eu%'"  > /dev/null 2>/dev/null 
		mysql -u $db_usr -p$db_urs_pwd $db_name -e "UPDATE field_revision_field_mgr_uri SET field_mgr_uri_value = replace(field_mgr_uri_value,'man.xtribe.eu','localhost') WHERE field_mgr_uri_value LIKE '%man.xtribe.eu%'"  > /dev/null 2>/dev/null 

		echo "--- Clearing Drupal cache..."
		cd /var/www/xtribe.eu/drupal
		drush cc all

		# in order to make the manager start with upstart the system must be restarted
		reboot_system
	fi
}

setup_htaccess() {
	cd /var/www/xtribe.eu/drupal
	cp .htaccess.editme .htaccess		
	echo "--- Setting domain rules"	
	if [ "$local_or_web" = "l" ]; then
		sed -i "s/RewriteCond.%{HTTP_HOST}.!^dev/#RewriteCond %{HTTP_HOST} !^dev/" .htaccess
		sed -i "s/RewriteCond.%{HTTP_HOST}.!^www/#RewriteCond %{HTTP_HOST} !^www/" .htaccess
		sed -i "s/RewriteRule.^.http:.*www.%{HTTP_HOST}%{REQUEST_URI}/#RewriteRule ^ http:\/\/www\.%{HTTP_HOST}%{REQUEST_URI}/" .htaccess
	fi
	if [ "$local_or_web" = "w" ]; then
		echo -n "Do you own a www domain? (y/n) "
		read yesno < /dev/tty
		while [ "$yesno" != "y" ] && [ "$yesno" != "n" ]; do
			echo -n "--- Please reply with a single characther: 'y' or 'n': "
			read yesno < /dev/tty
		done
			
		if [ "$yesno" = "y" ]; then
			sed -i "s/#*RewriteCond.%{HTTP_HOST}.!^dev/RewriteCond %{HTTP_HOST} !^dev/" .htaccess
			sed -i "s/#*RewriteCond.%{HTTP_HOST}.!^www/RewriteCond %{HTTP_HOST} !^www/" .htaccess
			sed -i "s/#*RewriteRule.^.http:.*www.%{HTTP_HOST}%{REQUEST_URI}/RewriteRule ^ http:\/\/www\.%{HTTP_HOST}%{REQUEST_URI}/" .htaccess
		else
			sed -i "s/RewriteCond.%{HTTP_HOST}.!^dev/#RewriteCond %{HTTP_HOST} !^dev/" .htaccess
			sed -i "s/RewriteCond.%{HTTP_HOST}.!^www/#RewriteCond %{HTTP_HOST} !^www/" .htaccess
			sed -i "s/RewriteRule.^.http:.*www.%{HTTP_HOST}%{REQUEST_URI}/#RewriteRule ^ http:\/\/www\.%{HTTP_HOST}%{REQUEST_URI}/" .htaccess
		fi
	fi	
}

setup_database_settingsphp() {
	echo "--- Setting database..."

	# During install or repair, database settings get asked
	if [ "$install" = "1" ] || [ "$repair" = "1" ]; then	
		cd /var/www/xtribe.eu/etsweb/default
		cp settings.php.editme settings.php
		
		echo "Please type your database settings. Your 'root' user, or an equally privileged user, is needed to create database and its user."
		echo -n "Database root user: "
		read db_root_usr < /dev/tty
		echo -n "Database root password: "
		read db_root_urs_pwd < /dev/tty
		#if [ "$local_or_web" = "l" ]; then
			db_host="localhost";
		#fi
		#if [ "$local_or_web" = "w" ]; then
		#	echo -n "Database host (ex.localhost): "
		#	read db_host < /dev/tty
		#fi		
		sed -i "s/.host..=>.*.,/\'host\' => \'$db_host\',/" settings.php

		# setting up settings.php
		sed -i "s/.username..=>.*.,/\'username\' => \'$db_usr\',/" settings.php
		sed -i "s/.password..=>.*.,/\'password\' => \'$db_urs_pwd\',/" settings.php	
		
		sed -i "s/.database..=>.*.,/\'database\' => \'$db_name\',/" settings.php
	fi

	# During installation, create db
	if [ "$install" = "1" ]; then
		echo "--- Creating and populating database... (May take a while)"	
		mysql -u $db_root_usr -p$db_root_urs_pwd -e "use $db_name"> /dev/null 2>/dev/null
		if [ $? = "0" ]; then
			setup_failed "Database already exists."
		else
			cd /var/www/xtribe.eu
			mysqladmin -u $db_root_usr -p$db_root_urs_pwd create $db_name || setup_failed "Could not create database."

			#  creating user to manage db
			mysql -u $db_root_usr -p$db_root_urs_pwd -e "GRANT ALL PRIVILEGES ON $db_name.* TO $db_usr@$db_host IDENTIFIED BY '$db_urs_pwd'"
			mysql -u $db_root_usr -p$db_root_urs_pwd -e "FLUSH PRIVILEGES"
		fi
	fi
	
	if [ "$update" = "1" ] || [ "$repair" = "1" ];then
		echo "--- Updating database... (May take a while)"
	fi
	if [ "$update" = "1" ] || [ "$repair" = "1" ] || [ "$install" = "1" ];then
		cd /var/www/xtribe.eu/etsinstall
		# loading structure (so eventually new tables get added) and general data
		mysql -u $db_usr -p$db_urs_pwd $db_name < db_structure.sql || setup_failed "Database failed initialization."		
		mysql -u $db_usr -p$db_urs_pwd $db_name < db_general_data.sql || setup_failed "Database failed updating."
	fi
}

setup_ets() {
	echo "--- Setting ETS..."
	cd /var/www/xtribe.eu/ets/conf
	cp config.json.template config.json

	# Parameters are stored in config.json and in drupal variables, using drush 	
	echo "Please choose your settings. ETS secret key is a password that ETS will use for security issues."
	echo -n "ETS secret key: "
	read ets_key < /dev/tty	
	sed -i "s/.ets_key.:.*,/\"ets_key\": \"$ets_key\",/" config.json
	
	if [ "$local_or_web" = "l" ]; then
		ip_domain="localhost";
	fi
	if [ "$local_or_web" = "w" ]; then
		echo -n "Your domain ip (ex.142.67.19.2): "
		read ip_domain < /dev/tty
	fi	

	sed -i "s/.endpoint.:.*:80.,/\"endpoint\": \"http:\\\\\/\\\\\/$ip_domain:8080\",/" config.json
	sed -i "s/.endpoint.:.*:6701.,/\"endpoint\": \"$ip_domain:6701\",/" config.json
	sed -i "s/.endpoint.:.*:6721.,/\"endpoint\": \"$ip_domain:6721\",/" config.json
	sed -i "s/.endpoint2.:.*:6722.,/\"endpoint2\": \"$ip_domain:6722\",/" config.json

	cd /var/www/xtribe.eu/drupal
	msg=`drush vset --yes ets_key "$ets_key" 2>&1`
	echo "$msg" | grep -w "error" && echo "$msg" && setup_failed "Error configuring Drupal." 
	msg=`drush vset --yes ets_redis_host_port "$ip_domain:6379" 2>&1`
	echo "$msg" | grep -w "error" && echo "$msg" && setup_failed "Error configuring Drupal." 
	msg=`drush vset --yes ets_ehs_host_port "$ip_domain:6701" 2>&1`
	echo "$msg" | grep -w "error" && echo "$msg" && setup_failed "Error configuring Drupal." 
	msg=`drush vset --yes ets_mhs_host_port1 "$ip_domain:6721" 2>&1`
	echo "$msg" | grep -w "error" && echo "$msg" && setup_failed "Error configuring Drupal." 	
	msg=`drush vset --yes ets_mhs_host_port2 "$ip_domain:6722" 2>&1`
	echo "$msg" | grep -w "error" && echo "$msg" && setup_failed "Error configuring Drupal." 	
}

setup_drupal_admin_pwd(){
	echo "--- Setting Drupal..."
	echo "Please choose your drupal settings."
	echo -n "Drupal admin password: "
	read drupal_pwd < /dev/tty	
	cd /var/www/xtribe.eu/drupal	
	
	msg=`drush upwd admin --password="$drupal_pwd" 2>&1`
	echo "$msg" | grep -w "error" && echo "$msg" && setup_failed "Error configuring Drupal." 
	# || echo 'Not found' # cioè non c'è stato errore
}

uninstall_xtribe(){
	echo "--- Uninstalling Xtribe..."
	# Remove db, keep user (uncorrect but who cares?)
	#if [ "$error_failed_setup" = "0" ]; then
	#	echo "Please type your database settings. Your 'root' user, or an equally privileged user, is needed to delete db and its user."
	#	echo -n "Database root user: "
	#	read db_root_usr < /dev/tty
	#	echo -n "Database root password: "
	#	read db_root_urs_pwd < /dev/tty
	#	if [ "$local_or_web" = "l" ]; then
	#		db_host="localhost";
	#	fi
	#	if [ "$local_or_web" = "w" ]; then
	#		echo -n "Database host (ex.localhost): "
	#		read db_host < /dev/tty
	#	fi
	#fi
	# se si tratta di una pulizia dopo un errore durante l'installazione
	# se ho i dati del db vuol dire che si è arrivati a installarlo e quindi va 'pulito'
	# altrimenti no
	#if [ "db_root_usr" != "" ] && [ "db_root_urs_pwd" != "" ] && [ "db_host" != "" ]; then
		mysql -u $db_usr -p$db_urs_pwd -e "DROP DATABASE IF EXISTS xtribe"  > /dev/null 2>/dev/null
		#mysql -u $db_root_usr -p$db_root_urs_pwd -e "DROP USER 'xtribe'@'$db_host'"  > /dev/null 2>/dev/null	
	#fi

	for i in $(seq 0 $limit_array);
		do
	  	mysql -u "${db_user_games[i]}" -p"${db_password_games[i]}" -e "DROP DATABASE IF EXISTS ${db_name_games[i]}"  #> /dev/null 2>/dev/null
	done	

	# Remove files	
	cd /var/www
	rm -rf xtribe.eu > /dev/null 2>/dev/null
	cd /etc/init
	rm ets-haproxy.conf > /dev/null 2>/dev/null	
	rm ets-server.conf > /dev/null 2>/dev/null	
	cd /etc/init.d/
	rm redis-server > /dev/null 2>/dev/null
	cd /etc/apache2/sites-available
	rm xtribe > /dev/null 2>/dev/null
	rm xtribe.conf > /dev/null 2>/dev/null
	cd /etc/apache2/sites-enabled
	unlink xtribe > /dev/null 2>/dev/null	
	unlink xtribe.conf > /dev/null 2>/dev/null

	# Remove apache configuration
	a2ensite default > /dev/null 2>/dev/null
	service apache2 restart  > /dev/null 2>/dev/null
}

################################ SCRIPT BEGINNING 
# Check if i am superuser
if [ "$(id -u)" != "0" ] ; then
	setup_failed "Please run it as superuser."
else
	# Check if i'm installing or updating or whatever
	if [ "${1}" != "install" ] && [ "${1}" != "update" ] && [ "${1}" != "repair" ] && [ "${1}" != "uninstall" ] && [ "${1}" != "install_games" ] && [ "${1}" != "install_managers" ]; then
		setup_failed "Please run specifying one of the available parameters: 'install', 'install_games', 'install_managers', 'repair', 'update', 'uninstall'."
	fi

	# Setup parameters for install and update
	#if [ "${1}" = "install" ]; then
	#	install="1"
	#	install_or_update="Setup"

	#	echo -n "Are you sure you want to install Xtribe? (y/n) "
	#	read continue_confirm < /dev/tty
	#	while [ "$continue_confirm" != "y" ] && [ "$continue_confirm" != "n" ]; do
	#		echo -n "--- Please reply with a single characther: 'y' or 'n': "
	#		read continue_confirm < /dev/tty
	#	done
	#	if [ "$continue_confirm" = "n" ]; then
	#		exit_cause "Installation interrupted by the user."
	#	fi
	#fi
	
	if [ "${1}" = "install" ]; then 
		install="1"
	fi
	
	if [ "${1}" = "install_managers" ] || [ "${1}" = "install_games" ]; then 
		install_or_update="Update"
	fi

	if [ "${1}" = "update" ]; then 
		update="1"
		install_or_update="Update"
		echo "$op_line Updating Xtribe... $close_line" 

		echo -n "Are you sure you want to update Xtribe? (y/n) "
		read continue_confirm < /dev/tty
		while [ "$continue_confirm" != "y" ] && [ "$continue_confirm" != "n" ]; do
			echo -n "--- Please reply with a single characther: 'y' or 'n': "
			read continue_confirm < /dev/tty
		done
		if [ "$continue_confirm" = "n" ]; then
			exit_cause "Update interrupted by the user."
		fi
	fi
	if [ "${1}" = "uninstall" ]; then 
		uninstall="1"
		install_or_update="Uninstall"
		echo "$op_line Uninstalling Xtribe... $close_line" 

		echo -n "Are you sure you want to uninstall Xtribe? ATTENTION: This will delete permanently xtribe files and database. (y/n) "
		read continue_confirm < /dev/tty
		while [ "$continue_confirm" != "y" ] && [ "$continue_confirm" != "n" ]; do
			echo -n "--- Please reply with a single characther: 'y' or 'n': "
			read continue_confirm < /dev/tty
		done
		if [ "$continue_confirm" = "n" ]; then
			exit_cause "Uninstall interrupted by the user."
		fi	
	fi
	if [ "${1}" = "repair" ]; then 
		repair="1"
		install_or_update="Repair"
		echo "$op_line Repairing Xtribe... $close_line" 

		echo -n "Are you sure you want to reset all Xtribe settings? (y/n) "
		read continue_confirm < /dev/tty
		while [ "$continue_confirm" != "y" ] && [ "$continue_confirm" != "n" ]; do
			echo -n "--- Please reply with a single characther: 'y' or 'n': "
			read continue_confirm < /dev/tty
		done
		if [ "$continue_confirm" = "n" ]; then
			exit_cause "Repair interrupted by the user."
		fi
	fi
	if [ "${1}" = "repair" ] || [ "${1}" = "install" ]; then 
		echo -n "$op_line Xtribe can be installed locally or in web mode. Locally it will work only on your machine. In web mode, it will be online, but you will need a valid web domain to host it. Do you want a local or web installation of Xtribe? (l/w) "
		read local_or_web < /dev/tty
		while [ "$local_or_web" != "l" ] && [ "$local_or_web" != "w" ]; do
			echo -n "--- Please reply with a single characther: 'l' or 'w': "
			read local_or_web < /dev/tty
		done	
	fi
	if [ "${1}" = "update" ] || [ "${1}" = "uninstall" ]; then 
		check_xtribe_is_installed_or_exit
		cd /var/www/xtribe.eu		
		local_or_web=`cat install.txt`
	fi
	# Create dir, initializa repo, adding remote repo
	if [ "${1}" = "install" ] || [ "${1}" = "repair" ] || [ "${1}" = "install_games" ] || [ "${1}" = "install_managers" ]; then
		echo "$op_line Checking required software availability. $close_line"
		# check software required is installed	
		check_drush_is_installed		
		check_nodejs_is_installed
		check_npm_is_installed
		check_php5_is_installed
		check_mysql_is_installed
		check_haproxy_is_installed
		check_redis_is_installed
		check_upstart_is_installed
		check_apache2_is_installed
		check_git_is_installed	
		echo "$op_line All required software are available. $close_line"
	fi

	if [ "${1}" = "install" ] || [ "${1}" = "repair" ]; then
		echo "$op_line Starting Xtribe setup... $close_line"
		setup_repo	
	fi

	if [ "${1}" = "update" ] || [ "${1}" = "install" ] || [ "${1}" = "repair" ];  then  		
		update_data_from_repo
		store_xtribe_install_mode
		setup_database_settingsphp
	fi
	
	if [ "${1}" = "install" ] || [ "${1}" = "repair" ]; then
		setup_cronjob_backup_db
		setup_redis
		setup_haproxy		
		setup_htaccess
		setup_upstart
		setup_drupal_admin_pwd
		setup_ets
		setup_permission_on_all_files
		setup_apache2
	fi

	if [ "${1}" = "install" ] || [ "${1}" = "install_games" ]; then
		setup_games
	fi

	if [ "${1}" = "install" ] || [ "${1}" = "install_managers" ]; then
		setup_managers
	fi

	if [ "${1}" = "uninstall" ]; then 
		uninstall_xtribe	
	fi

	echo "$op_line Xtribe $install_or_update successfully completed. $close_line"
	if [ "${1}" = "install" ];  then  		
		reboot_system
	fi	
fi



#if { [ "${1}" = "update" ] || [ "${1}" = "install" ]; } && [ "$setupFailed" = "FALSE" ]; then 
