#!/bin/bash

## Initially Created by Michael Kubler at Grey Phoenix Productions Jan 2010
## Edited for ANAT on 2nd of Jan 2011
## Note, this is for creating new domains, and does not yet add ANAT subdomains (which are generally appended to the /etc/apache2/sites-available/anat config

## Please fill in the variables below if you would like to create the MySQL db for a WordPress blog
__MYSQL_ROOT_USER=''
__MYSQL_ROOT_PASSWORD=''


# This script should be run as root.
if [ "$UID" -ne 0 ]; then
  echo "Must be root to run this script."
  exit 1
fi  


CURRENT_DATE=$(date +%F)
CONFIG_INFO="" # This will be added to throughout the script and displayed at the end to the user
PASSWORD=$RANDOM #Used as the main password for anything that needs a password... Somewhat insecure but better than the alternative

## Other Variables used throughout the script (for general dev reference... Not complete).
#ADD_MAILMAN='y'
#ADD_FTP='y'
#ADD_WORDPRESS='y'
#CONFIRM_SETTINGS='y'
#ADD_FTP='y'
#CHANGE_TLD='y'
#EMAIL='tech@anat.org.au'
#TLD=array(.org.au .net.au .com)|'.com'
#MYSQL_PASSWORD="$RANDOM.timsp]-[$RANDOM"


#######################
## CHECK SITE LISTED ##
#######################
# Checks to ensure an actual site was listed, otherwise asks for one
 if [ -z "$1" ]; then # Then there was no argument passed to the creation script
     echo "[Note] This script creates the required apache /var/www/SITE_NAME/, /var/log/SITE_NAME/ and other stuff for a new website"
     echo "[Note] Usage : 'sudo createsite.sh SITE_NAME EMAIL_ADDRESS'"
     echo "[Note] Usage Example : 'sudo createsite.sh anat tech@anat.org.au'"
	 echo
     echo -n "* Please enter the site name (e.g 'anat' or 'isea2013') : "
     read SITE
     if [ "$SITE" == "" ]; then # No answer to the question (User just pressed space, or timed out)
		echo "[ERROR] No site listed. Now exiting"
		exit 2
     else
		echo "- Site set to www.$SITE.com"
     fi # End checking for user input
 else
	# The site was added on the command line #
	SITE=$1
	
	# Check if the email address was added on the command line
	if [ -z "$2" ]; then # Check if a second argument was provided.. the email address
		EMAIL=$2
		echo "[Note] Setting Admin email address to $EMAIL"
	fi
	echo "[Note] Creating site www.$SITE.com"
fi # End checking for 1st argument

## Give a quick overview of what will be happening ##
echo "[Note] This script will likely ask a number of questions about configuration and optional installs."
echo "These include :"
echo "# Admin email address"
echo "# Top Level Domain (e.g .com .biz .com.au, .net.au)"
echo "# FTP"
echo "# WordPress"
echo "# Mailman"
echo "# Confirm settings"
echo "It will also create a random password and display all the configuration information at the end, plus email it to the admin email address"
echo "[Note] Please check you have created the DNS for the domain and also configured this file with the MYSQL database user information (if you want the WordPress install)"


####################
## ASK ABOUT TLDs ##
####################

if [ "$EMAIL" == "" ]; then # Hasn't been set on the command line, so ask for it
	echo 
	echo -n "* What email address would you like to send the final information to (e.g tech@anat.org.au) ? "
	read EMAIL
	if [ "$EMAIL" == "" ]; then
		echo "[ERROR] No email address specified, try again" 
		echo -n "* TRY again. What email address would you like to set (e.g tech@anat.org.au) ? "
		read EMAIL
		if [ "$EMAIL" == "" ]; then
			echo "[ERROR] No email address specified, EXITING"
			exit 3
		fi # End checking if the email address was given on the 2nd attempt
	fi # End checking if the email address was given the first attempt
fi # End checking if $EMAIL alread set (on the command line)

echo -n "* The default domain is $SITE.com would you like to change the top level domain from '.com' ? [Y/n] : "
read -n 1 CHANGE_TLD
echo
if [ "$CHANGE_TLD" == "y" ] ; then
	echo "- Changing TLD"
	echo "[Note] When entering the top level domains the first TLD is the primary, and used for Mailman, etc.. the others will be aliases of the primary"
	echo
	echo -n "* Please enter the new TLDs, if multiple then ensure space separated (e.g .org.au .com .biz) : "
	read -a TLD
	echo
	if [ ${TLD[0]} == "" ]; then
		echo  -n "[Error] Incorrect or no answer, try again : "
		read -a TLD
		echo
		if [ ${TLD[0]} == "" ] ; then
			echo "[ERROR] Two incorrect attempts, setting back to defaults (.com). Try [Ctrl] + [c] to cancel and try again"
			TLD='.com'
		fi # End asking for TLD the 2nd time
	fi # End asking for TLD the 1st time
elif [ "$CHANGE_TLD" == "n" ] ; then # Not changing TLD
	echo "[Note] Not changing the TLD"
	TLD='.com'
else # Ummm... Not a y or a n
	echo "[Warning] Unknown answer, not changing the TLD"
	TLD='.com'
fi # End checking for CHANGE_TLD question

## List TLDS ##
if [ ${#TLD[@]}  -gt 1 ]; then # Then was given more than one Top Level Domain, so list them
echo "[Note] You've requested ${#TLD[@]} TLDs which are : "
CONFIG_INFO="$CONFIG_INFO\n==== SITES ====\nThe ${#TLD[@]} sites are :"
	for ix in ${!TLD[*]}
	do
		TLDS="$SITE${TLD[$ix]} " # Used for the Apache Config
	    echo "[$ix] www.$SITE${TLD[$ix]}"
		CONFIG_INFO="$CONFIG_INFO\n[$ix] http://www.$SITE${TLD[$ix]}/"
	done
else # Just a single domain
	echo "[Note] You've requested the single domain to be created as www.$SITE$TLD"
	CONFIG_INFO="$CONFIG_INFO\n==== SITE ====\nThe Site is www.$SITE$TLD\n"
fi # End checking for Top Level Domain(s)
CONFIG_INFO="$CONFIG_INFO\nLog files : /var/log/apache2/$SITE\nApache Config file : /etc/apache2/sites-available/$SITE\nDocument Root : /var/www/$SITE/www/\n"




##################
## FTP QUESTION ##
##################
echo
echo -n "* Would you like to configure an FTP user account for this domain? [y/n] : "
read -n 1 ADD_FTP
echo
if [ "$ADD_FTP" == "y" ]; then
	echo "- Will attempt to add the FTP account $SITE with a password of $PASSWORD"
	CONFIG_INFO="$CONFIG_INFO\n==== FTP ====\nFTP User : $SITE\nFTP Host : www.$SITE$TLD\nFTP Password : $PASSWORD\n[Note] Suggest using Active connection mode (versus PASV) if you can't view the folder contents\n"
elif [ "$ADD_FTP" == "n" ]; then
	echo "[Note] Not adding the FTP user account"
else
	echo "[Warning] Unknown answer, assuming you don't want FTP access"
	ADD_FTP='n'
fi




########################
## WordPress QUESTION ##
########################
echo
echo -n "* Would you like to to host a WordPress blog on this domain? [y/n] :"
read -n 1 ADD_WORDPRESS
echo
if [ "$ADD_WORDPRESS" == "y" ]; then
	echo "[Note] Will attempt to create a WordPress blog at www.$SITE$TLD"
	MYSQL_PASSWORD="$RANDOM.timsp]-[$RANDOM" #This is to prevent an FTP user from using the same password to hack the MySQL database
	echo "[Note] The MySQL DB password WordPress blog (which will be repeated later) will be : '$MYSQL_PASSWORD'"
	CONFIG_INFO="$CONFIG_INFO\n==== WordPress ====\nAddress : http://www.$SITE$TLD/\nAdmin login URL : http://www.$SITE$TLD/wp-admin/\nAdmin username : $SITE\nAdmin password : $PASSWORD\nMySQL database User : $SITE\nMySQL database Password : $MYSQL_PASSWORD\n"
elif [ "$ADD_WORDPRESS" == "n" ]; then
	echo "[Note] Not adding the FTP user account"
else
	echo "[Warning] Unknown answer, assuming you don't want a WordPress blog"
	ADD_WORDPRESS='n'
fi


######################
## MAILMAN QUESTION ##
######################
echo
echo -n "* Would you like to install a mailman mailing list to list.$SITE$TLD ? [y/n] : "
read -n 1 ADD_MAILMAN
echo
if [ "$ADD_MAILMAN" == "y" ]; then
	echo "- Will attempt to add the mailing lists $SITE-announce@list.$SITE$TLD and $SITE-discuss@list.$SITE$TLD"
	echo
	echo "- Setting Mailing list Email to $EMAIL and the PASSWORD to $PASSWORD"
	CONFIG_INFO="$CONFIG_INFO\n\n==== MAILMAN ====\nMailing List 1\n--------------\nEmail Address: $SITE-announce@list.$SITE$TLD\nSubscribe Page : http://list.$SITE$TLD/mailman/listinfo/$SITE-announce/\nAdmin Login : http://list.$SITE$TLD/mailman/admin/$SITE-announce/\nAdmin Email : $EMAIL\nAdmin Password : $PASSWORD\n"
	CONFIG_INFO="$CONFIG_INFO\n\nMailing List 2\n--------------\nEmail Address: $SITE-discuss@list.$SITE$TLD\nSubscribe Page : http://list.$SITE$TLD/mailman/listinfo/$SITE-discuss/\nAdmin Login : http://list.$SITE$TLD/mailman/admin/$SITE-discuss/\nAdmin Email : $EMAIL\nAdmin Password : $PASSWORD\n"
elif [ "$ADD_MAILMAN" == "n" ]; then
	echo "[Note] Not adding a Mailing list"
else
	echo "[Warning] Unknown answer, assuming no mailing list"
	ADD_MAILMAN='n'
fi




######################
## CONFIRM SETTINGS ##
######################
echo
echo "[Note] Will now confirm your settings"
echo "====================================="
## List TLDS ##
if [ ${#TLD[@]}  -gt 1 ]; then
echo "	${#TLD[@]} sites being created : "
	for ix in ${!TLD[*]}
	do
	    echo "	* www.$SITE${TLD[$ix]}"
	done
	echo
else
	echo "	Site : www.$SITE$TLD"
fi
if [ "$ADD_MAILMAN" == "y" ]; then
	echo "	Create Mailing Lists : Yes"	
else
	echo "	Create Mailing lists : No"
fi

if [ "$ADD_FTP" == "y" ]; then
	echo "	Create FTP : Yes"
else
	echo "	Create FTP : No"
fi # End outputing FTP config settings

if [ "$ADD_WORDPRESS" == "y" ]; then
	echo "	Create WordPress : Yes"
	echo "	WordPress Database Password : $MYSQL_PASSWORD"
else
	echo "	Create WordPress : No"
fi # End outputing WordPress config settings

echo ""
echo "	Primary Password : $PASSWORD"
echo "	Email : $EMAIL"
echo -n "* Are these settings correct? [y/n] : "
read -n 1 CONFIRM_SETTINGS
echo
if [ "$CONFIRM_SETTINGS" == "y" ]; then
	echo "- Excelent. Done with the questioning, now to the making"
	sleep 1 #Give the user a second to read the line and give them a chance to cancel
elif [ "$CONFIRM_SETTINGS" == "n" ]; then
	echo "[Warning] Settings incorrect, now exiting!"
	exit 1
else
	echo "[ERROR] Unknown answer, assuming you are mashing the keyboard and the settings are incorrect. Now Exiting!"
	exit 4
fi # End confirming settings


###############################################################################################################################
#############################################
## CREATE THE APACHE SITE CONF AND FOLDERS ##
#############################################

cd /var/www
echo "----------------------------------"

################
# try_mkdir() ##
################
# This is a small helper function to try making a directory nicely erroring ##
# @input string directory
# @output echo string if created or already created
function try_mkdir
{
	if [ -d "$1" ]; then
		echo "[warn] Directory '$1' already created"
	else
		mkdir $1
		echo "- Created directory $1"
	fi
}
#---------------------------------#




###################
# site_aliases() ##
###################
# Used for the Apache Config
# @input string subdomain (e.g 'list.' or 'www.')
# @return string e.g 'list.anat.org.au list.anat.com list.anat.net'
function site_aliases
{
	__ALIASES=''
	# Clear out the variable in case it was used once already
	for ix in ${!TLD[*]}
	do
		__ALIASES="$__ALIASES $1$SITE${TLD[$ix]}" 
	done
	echo $__ALIASES
## As per http://www.linuxjournal.com/content/return-values-bash-functions
# $(site_aliases list.)
}
#---------------------------------#

try_mkdir /var/www/$SITE/
try_mkdir  /var/www/$SITE/www
try_mkdir /var/www/$SITE/staging
try_mkdir /var/www/$SITE/staging/www
try_mkdir /var/www/$SITE/stats
try_mkdir /var/log/apache2/$SITE

if [ "$ADD_MAILMAN" == "y" ]; then
	try_mkdir /var/www/$SITE/list
fi

echo "- Created the web folders"

## Setting File permissions on the created folders ##
chown www-data:www-data -R /var/www/$SITE/
echo "- Done settings folder permissions"
sleep 0.5 # Give the user a moment to ensure everything is OK


########################
## CREATE FTP ACCOUNT ##
########################
# If previously set will create the default FTP files and folders and try to setup the FTP account.

if [ "$ADD_FTP" == "y" ]; then
	echo "# FTP #"
	echo "[Note] Now Processing the FTP creation"
	#mkdir /home/ftpusers/
	## TO DO -- If PureFTP isn't installed try installing it?
	
	try_mkdir /home/ftpusers/$SITE
	if [ -d /home/ftpusers/$SITE ]; then
		ln -s /var/www/$SITE/ /home/ftpusers/$SITE
		ln -s  /var/log/apache2/$SITE/ /home/ftpusers/$SITE/${SITE}-logs
		touch /home/ftpusers/$SITE/created_$CURRENT_DATE
		echo "- Created the FTP symbolic links, now creating the FTP account"
	else
		echo "[Error] Unable to create FTP account directory /home/ftpusers/$SITE"
		CONFIG_INFO="$CONFIG_INFO\n#----- [FTP : DIRECTORY CREATION ERROR] -----#\n[Error] Unable to create FTP account directory /home/ftpusers/$SITE\n[Warning] You will also need to create the following symbolic links :\n> ln -s /var/www/$SITE/ /home/ftpusers/$SITE\n> ln -s  /var/log/apache2/$SITE/ /home/ftpusers/$SITE/${SITE}-logs\n> touch /home/ftpusers/$SITE/created_$CURRENT_DATE\n"
	fi # End creating FTP user directory
	
	
	# Note : Does not yet have an FTP account"
	which expect
	if [ $? -gt 0 ]; then
		echo "[Warning] Need to install Expect in order to setup the FTP account in non-interactive mode"
		apt-get update
		apt-get install expect
		if [ $? -lt 1 ]; then # Install failed
			echo "[Error] Unable to Create the FTP account in non-interactive mode, we are going to need your fingers"
			echo "*********************************"
			echo "** ERROR Creating FTP Account **"
			echo "********************************"
			echo "[Error] Can't install expect so can't automatically create the Pure-FTPd account"
			echo "Please follow the instructions below in order to create the FTP account"
			echo "When asked, please enter '$PASSWORD' (without quotes) as the password."
			echo "You will need to enter it in twice and press enter after each time"
			echo "Remember : Enter the password $PASSWORD"
			echo
			pure-pw useradd $SITE -u ftpuser -d /home/ftpusers/$SITE
			if [ $? -gt 0 ]; then
				echo "[Error] The PureFTPd account was not configured correctly"
				CONFIG_INFO="$CONFIG_INFO\n#----- [FTP : CONFIG ERROR] -----#\n[Error] Unable to create FTP account\n[Warn] You will need to run the following to configure the FTP account :\n> pure-pw useradd $SITE -u ftpuser -d /home/ftpusers/$SITE\n"
			fi # End checking the user input the correct details
		fi # End trying to install Expect
	fi # End 1st pass at trying to use Expect
	
	## Try expect again to see if it was created ##
	which expect
	if [ $? -eq 0 ]; then
		echo "[Note] Trying to add the FTP account in non-interactive mode using Expect"
		# This requires expect and an expects file in order to be able to add the ftp password.
		### CREATE THE EXPECT FILE ###
		echo '#!/usr/bin/expect' > temp_expect_file.temp
		echo "spawn pure-pw useradd $SITE -u ftpuser -d /home/ftpusers/$SITE/ " >> temp_expect_file.temp
		echo 'expect "^Password:"' >> temp_expect_file.temp
		echo -n 'exp_send "' >> temp_expect_file.temp
		echo -n $PASSWORD >> temp_expect_file.temp
		echo '\n"' >> temp_expect_file.temp
		echo 'expect "nter it again:"' >> temp_expect_file.temp
		echo -n 'exp_send "' >> temp_expect_file.temp
		echo -n $PASSWORD >> temp_expect_file.temp
		echo -n '\n"' >> temp_expect_file.temp
		echo '' >> temp_expect_file.temp
	else # Nope, still can't use expect #
		echo "[Error] The PureFTPd account was not configured correctly"
		CONFIG_INFO="$CONFIG_INFO\n#----- [FTP : CONFIG ERROR] -----#\n[Error] Unable to create FTP account\n[Warn] You will need to run the following to configure the FTP account :\n> pure-pw useradd $SITE -u ftpuser -d /home/ftpusers/$SITE\n"
		## The above code creates a temporary expects file which runs the pure-pw program then attempts to automatically add the account password details
		## The except file should look similar to the following :

		#!/usr/bin/expect
		#spawn pure-pw useradd anat -u ftpuser -d /home/ftpusers/anat/
		#expect "^Password:"
		#exp_send "11415\n"
		#expect "nter it again:"
		#exp_send "11415\n"

		## RUN THE EXPECT FILE ##
		chmod u+x temp_expect_file.temp
		./temp_expect_file.temp
		if [ $? -gt 0 ]; then # Running the expect file failed, will have to create the account manually (getting the user to type the password)
			echo "*********************************"
			echo "** ERROR Creating FTP Account **"
			echo "********************************"
			echo "[Error] Couldn't automatically create Pure-FTPd account"
			echo "Please follow the instructions below in order to create the FTP account"
			echo "When asked, please enter '$PASSWORD' (without quotes) as the password."
			echo "You will need to enter it in twice and press enter after each time"
			echo "Remember : Enter the password $PASSWORD"
			echo
			pure-pw useradd $SITE -u ftpuser -d /home/ftpusers/$SITE
			echo "[Error] The PureFTPd account was not configured correctly"
			CONFIG_INFO="$CONFIG_INFO\n#----- [FTP : CONFIG ERROR] -----#\n[Error] Unable to create FTP account\n[Warn] You will need to run the following to configure the FTP account :\n> pure-pw useradd $SITE -u ftpuser -d /home/ftpusers/$SITE\n"
		fi # End manual PureFTP configure
	fi # End expect attempt at PureFTP account creation
	
	rm temp_expect_file.temp # Remove the temporary expect file, especially as it contains the password.
	chown -R ftpuser:ftpgroup /home/ftpusers/$SITE
	pure-pw mkdb
	
	## Attempt to restart PureFTP
	if [ -f /etc/init.d/pure-ftpd ]; then
		echo "Restarting PureFTPd"
		/etc/init.d/pure-ftpd restart
	fi # End restarting Pure-FTPd (if the init.d file is there)
	echo "- Done configuring FTP"
fi # End FTP install

## Done with the FTP creation ##
#--------------------------------------------------------------------------------------------#




#######################
## WordPress INSTALL ##
#######################
#======================================================================#
# This was initially a custom made script for updating multiple WordPress sites to the latest version and was created by Michael Kubler for Grey Phoenix Productions ( Jan 18th 2010 )

if [ "$ADD_WORDPRESS" == "y" ]; then
	echo "# WordPress #"
	echo "[Note] Now Processing the WordPress blog creation"
	cd /var/www/$SITE/www/
	wget http://wordpress.org/latest.tar.gz #Download the latest version of WordPress from the site NB : this URL might need to be updated in the future if they change it.

	if [ -f /var/www/$SITE/www/latest.tar.gz ]; 
	then
		tar -zxf latest.tar.gz # Unzip the file
		rm latest.tar.gz
		cd wordpress
		mv * ../ # Unzipping the file created the WordPress directory, which we are getting rid of.
		cd ../
		rmdir wordpress
		
		echo " - Done installing WordPress"
		touch /var/www/$SITE/www/wp-config.php
		## The WordPress Config... Note that if WordPress change the default config, then you'll need to change this
		# Note to self heredoc suggestion came from http://tldp.org/LDP/abs/html/here-docs.html
		
		cat > /var/www/$SITE/www/wp-config.php << END-of-CONFIG
<?php
/**
 * The base configurations of the WordPress.
 *
 * This file has the following configurations: MySQL settings, Table Prefix,
 * Secret Keys, WordPress Language, and ABSPATH. You can find more information
 * by visiting {@link http://codex.WordPress.org/Editing_wp-config.php Editing
 * wp-config.php} Codex page. You can get the MySQL settings from your web host.
 *
 * This file is used by the wp-config.php creation script during the
 * installation. You don't have to use the web site, you can just copy this file
 * to wp-config.php and fill in the values.
 *
 * @package WordPress
 */

// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', '$SITE');

/** MySQL database username */
define('DB_USER', '$SITE');

/** MySQL database password */
define('DB_PASSWORD', '$MYSQL_PASSWORD');

/** MySQL hostname */
define('DB_HOST', 'localhost');

/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');

/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');

/**#@+
 * Authentication Unique Keys and Salts.
 *
 * Change these to different unique phrases!
 * You can generate these using the {@link https://api.WordPress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
 * You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
 *
 * @since 2.6.0
 */
define('AUTH_KEY',         '$RANDOM.asdfasd$RANDOM');
define('SECURE_AUTH_KEY',  '$RANDOM.basdfd4fasd$RANDOM');
define('LOGGED_IN_KEY',    '$RANDOM.csd3423ffsd$RANDOM');
define('NONCE_KEY',        '$RANDOM.ds2d9r67j$RANDOM');
define('AUTH_SALT',        '$RANDOM.zs354sd$RANDOM');
define('SECURE_AUTH_SALT', '$RANDOM.f42134fasd$RANDOM');
define('LOGGED_IN_SALT',   '$RANDOM.j23?5fasd$RANDOM');
define('NONCE_SALT',       '$RANDOM.ms+asd$RANDOM');

/**#@-*/

/**
 * WordPress Database Table prefix.
 *
 * You can have multiple installations in one database if you give each a unique
 * prefix. Only numbers, letters, and underscores please!
 */
\$table_prefix  = 'wp_';

/**
 * WordPress Localized Language, defaults to English.
 *
 * Change this to localize WordPress.  A corresponding MO file for the chosen
 * language must be installed to wp-content/languages. For example, install
 * de.mo to wp-content/languages and set WPLANG to 'de' to enable German
 * language support.
 */
define ('WPLANG', '');

/**
 * For developers: WordPress debugging mode.
 *
 * Change this to true to enable the display of notices during development.
 * It is strongly recommended that plugin and theme developers use WP_DEBUG
 * in their development environments.
 */
define('WP_DEBUG', false);

/* That's all, stop editing! Happy blogging. */

/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
      define('ABSPATH', dirname(__FILE__) . '/');

/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');
END-of-CONFIG
		## End of the WordPress config file
		
		if [ -f /var/www/$SITE/www/wp-config.php ]; # Check the config file was created
		then
			chmod 400 /var/www/$SITE/www/wp-config.php # Set strict file permissions
			chown www-data:www-data /var/www/$SITE/www/wp-config.php
			echo " - Done configuring WordPress"
		else
			echo "[Error] Unable to create WordPress config file /var/www/$SITE/www/wp-config.php"
			echo "[Warn] You will need to check file and folder permissions and try using the online configurator at http://www.$SITE$TLD/"
			CONFIG_INFO="$CONFIG_INFO\n #----- [WordPress : INSTALL - CONFIG ERROR] -----#\n[ERROR] Unable to create WordPress config file\n[Warn] To get WordPress working please use the online configurator at http://www.$SITE$TLD/\n"
		fi # End checking wp-config.php file installed
		
		
		### WordPress MySQL ###
		MYSQL_SQL="CREATE USER '$SITE'@'localhost' IDENTIFIED BY '15463.timsp]-[11365';\n
GRANT USAGE ON \052.\052 TO '$SITE'@'localhost' IDENTIFIED BY '15463.timsp]-[11365' WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;\n
CREATE DATABASE IF NOT EXISTS $SITE;\n
GRANT ALL PRIVILEGES ON $SITE.* TO '$SITE'@'localhost';"
		## Note. I had a LOT of issues getting the *.* to be echo'd correctly as no matter what, it would interpret it and display a list of files in the directory.
		# I've opted for outputting the ASCII equivalent (which gets interpreted as *)
		##// Note to self. Ascii chars output taken from http://www.linuxquestions.org/questions/programming-9/bash-printing-extended-ascii-characters-286242/

		# ASCII NUMBER = CHARACTE
		#\052 = * (Star)
		#\0264 = ` (Back Quote?)... Damn, not a backtick
		#\0140 = ` (Another Back Quote?)

		## APPLY THE MYSQL! ##
		echo -e $MYSQL_SQL | mysql -u$__MYSQL_ROOT_USER -p$__MYSQL_ROOT_PASSWORD

		if [ $? -gt 0 ];
		then
			echo "#----- [WordPress : MYSQL ERROR] -----#"
			echo "[ERROR] UNABLE TO CREATE MYSQL USER OR DATABASE"
			echo "[Note] To get WordPress working please create a MySQL database user called $SITE with a password of $MYSQL_PASSWORD"
			CONFIG_INFO="$CONFIG_INFO\n #----- [WordPress : INSTALL ERROR] -----#\n[ERROR] UNABLE TO CREATE MYSQL USER OR DATABASE\n[Warn] To get WordPress working please create a MySQL database user called $SITE with a password of $MYSQL_PASSWORD\n[Note] The required SQL is : \n/****************/\n$MYSQL_SQL\n/****************/\n"
		else
			echo " - Done configuring MySQL for WordPress"
		fi # End of MySQL Error
	else # File didn't download.
		echo "#----- [WordPress : INSTALL - DOWNLOAD ERROR] -----#"
		echo "[Error] Unable to download latest WordPress install from http://WordPress.org/latest.tar.gz"
		CONFIG_INFO="$CONFIG_INFO\n#----- WordPress INSTALL ERROR -----#\n[Error] Unable to download latest WordPress install from http://WordPress.org/latest.tar.gz\n[Suggestion] Please check your Internet connection and try manually installing WordPress later\n"
	fi # End of checking the file downloaded
echo " - Done installing and configuring WordPress"
fi # End of WordPress install

#--------------------------------------------------------------------------------------------#









####################
## MAILMAN CONFIG ##
####################
#======================================================================#

if [ "$ADD_MAILMAN" == "y" ];
then
	echo "# Mailman #"
	echo "[Note] Now Processing the Mailman email lists creation"
	
	## Create the Mailman Mailing List ##
	which newlist
	if [ $? -gt 0 ]; then # Can't find the mailman create list command
	# Note : $? is the error code of the last run command, in this case seeing where the command newlist is.. If the return code = 0 then it worked fine and this part won't be run
	# If the error code is greater than 0 (-gt = greater than the number) it runs the following commands, letting the admin know we couldn't create the mailing list 
		echo "[ERROR] You do not have Mailman installed, or the newlist command is not available."
		echo "[Warn] Did not create the Mailman mailing list"
		CONFIG_INFO="$CONFIG_INFO\n#----- [MAILMAN : LIST CREATION ERROR] -----#\n[Error] You do not have Mailman installed, or the newlist command is not available.\n[Warn] Did not create the Mailman mailing list\n[Notice] If you would like to create the mailman mailing list use the following commands :\n> newlist -q --urlhost=list.$SITE$TLD --emailhost=list.$SITE$TLD $SITE-announce $EMAIL $PASSWORD\n> newlist -q --urlhost=list.$SITE$TLD --emailhost=list.$SITE$TLD $SITE-discuss  $EMAIL $PASSWORD\n"
	else # You've got mailman!
	
		newlist -q --urlhost=list.$SITE$TLD --emailhost=list.$SITE$TLD $SITE-announce $EMAIL $PASSWORD
		newlist -q --urlhost=list.$SITE$TLD --emailhost=list.$SITE$TLD $SITE-discuss  $EMAIL $PASSWORD
		
		if [ $? -gt 0 ]; then # Failed to create the mailman mailing list
			echo "[ERROR] Unable to create the new Mailman mailing list(s)"
			CONFIG_INFO="$CONFIG_INFO\n#----- [MAILMAN : MAILING LIST INSTALL ERROR] -----#\n[ERROR] Unable to create the new Mailman mailing list(s)[Notice] If you would like to create the mailman mailing list use the following commands :\n> newlist -q --urlhost=list.$SITE$TLD --emailhost=list.$SITE$TLD $SITE-announce $EMAIL $PASSWORD\n> newlist -q --urlhost=list.$SITE$TLD --emailhost=list.$SITE$TLD $SITE-discuss  $EMAIL $PASSWORD\n"
		else # Created the mailing list OK
			echo " - Done installing the Mailman mailing lists"
		fi # End checking if the mailing list was created ok.
		
		
		
		## Update the EXIM4 Config file ##
		which exim4
		if [ $? -gt 0 ]; then # Then Exim4 isn't installed
			echo "[ERROR] Exim4 not installed or unable to find it"
			echo "[WARNING] Unabled to configure the SMTP server for the Mailman mailing list"
			CONFIG_INFO="$CONFIG_INFO\n#----- [MAILMAN : EXIM4 CONFIGURATION ERROR] -----#\n[ERROR] Unable to find Exim4\n[Note] If you are running Postfix, Sendmail or something other than Exim4 for SMTP (email), then you will need to configure it yourself\n[Suggestion] If running Exim4 please run the following commands to manually add list.$SITE$TLD to the dc_other_hostnames :\n> sudo nano /etc/exim4/update-exim4.conf.conf\nPlease add list.$SITE$TLD to the end of the 'domainlist mm_domains' line using :\n> sudo nano /etc/exim4/conf.d/main/04_exim4-config_mailman\n"
		else
			## Update the EXIM4 config file ##
			if [ -f /etc/exim4/update-exim4.conf.conf ]; then
				cp /etc/exim4/update-exim4.conf.conf /etc/exim4/update-exim4.conf.conf.backup # Can't sed update the same file, and backing up the file is a good idea.
				# The command below uses SED (Stream Editor) to add the list domain to the dc_other_hostnames variable used by Exim4
				sed -e "s/dc_other_hostnames='[a-z/.:0-9-]*/&:list.$SITE$TLD/" < /etc/exim4/update-exim4.conf.conf.backup > /etc/exim4/update-exim4.conf.conf
				fgrep list.$SITE$TLD /etc/exim4/update-exim4.conf.conf
				if [ $? -gt 0 ]; then
					echo "[ERROR] Unable to add list.$SITE$TLD to the Exim4 dc_other_hostnames variable in the file /etc/exim4/update-exim4.conf.conf"
					CONFIG_INFO="$CONFIG_INFO\n#----- [MAILMAN : EXIM4 CONFIGURATION ERROR] -----#\n[ERROR] Unable to add list.$SITE$TLD to the Exim4 dc_other_hostnames variable in the file /etc/exim4/update-exim4.conf.conf\n[Note] If you are running Postfix, Sendmail or something other than Exim4 for SMTP email, then you will need to configure it yourself\n[Suggestion] If running Exim4 please run the following commands to manually add list.$SITE$TLD to the dc_other_hostnames :\n> sudo nano /etc/exim4/update-exim4.conf.conf\nPlease add list.$SITE$TLD to the end of the 'domainlist mm_domains' line using :\n> sudo nano /etc/exim4/conf.d/main/04_exim4-config_mailman\n"
				else
					echo " - Done configuring Exim4 config file 1/2"
				fi # End checking if the sed actually worked
			else # Else main config file doesn't exist
				echo "[ERROR] Unable to find the main Exim4 Config file which should be at /etc/exim4/update-exim4.conf.conf"
				CONFIG_INFO="$CONFIG_INFO\n#----- [MAILMAN : EXIM4 CONFIGURATION ERROR] -----#\n[ERROR] Unable to find the main Exim4 Config file which should be at /etc/exim4/update-exim4.conf.conf\n[WARNING] Unable to add list.$SITE$TLD to the Exim4 dc_other_hostnames variable in the file /etc/exim4/update-exim4.conf.conf\n[Note] If you are running Postfix, Sendmail or something other than Exim4 for SMTP email, then you will need to configure it yourself\n"
			fi # End checking if the Exim4 config file exists
			
			
			
			
			## Update the EXIM4 Mailman file ##
			if [ -f /etc/exim4/conf.d/main/04_exim4-config_mailman ]; then
				cp /etc/exim4/conf.d/main/04_exim4-config_mailman /etc/exim4/conf.d/main/04_exim4-config_mailman.backup # Can't sed update the same file, and backing up the file is a good idea.
				# The command below uses SED to add the list domain to a specified mailman variable used by Exim4
				sed -e "s/domainlist mm_domains=.*/& list.$SITE$TLD/" < /etc/exim4/conf.d/main/04_exim4-config_mailman.backup > /etc/exim4/conf.d/main/04_exim4-config_mailman
				echo " - Done configuring Exim4 config file 2/2"
			else
				echo "[ERROR] Unable to add list.$SITE$TLD to the Exim4 'domainlist mm_domains' variable in the file /etc/exim4/conf.d/main/04_exim4-config_mailman. Are you running Exim4 using a monolithic config file?"
				CONFIG_INFO="$CONFIG_INFO\n#----- [MAILMAN : EXIM4 CONFIGURATION ERROR] -----#\n[ERROR] Unable to add list.$SITE$TLD to the Exim4 'domainlist mm_domains' variable in the file/etc/exim4/conf.d/main/04_exim4-config_mailman\n[Note] If you are running Exim4 in monolthic config file mode you will need to configure it yourself\n"
			fi
			
			## Update Exim4 with the new config ##
			update-exim4.conf
			
			## Restart Exim4 to ensure it defintely has picked up the mailman domain (Note: I sometimes have issues with this) ##
			/etc/init.d/exim4 restart
			
			## Confirm the routing is via mailman ##
			exim -bt $SITE-discuss@list.$SITE$TLD
			if [ $? -gt 0 ]; then
				echo "[ERROR] Exim4 unable to route emails to $SITE-discuss@list.$SITE$TLD"
				echo "[Warn] Exim4 not configured correctly"
				CONFIG_INFO="$CONFIG_INFO\n#----- [MAILMAN : EXIM4 ROUTING ERROR] -----#\n[Error] Exim4 is unable to route to $SITE-discuss@list.$SITE$TLD Check DNS and the configuration files and try again\n[Note] Once you have configured Mailman and Exim4 correctly run the following to test (note that the mx records for list.$SITE$TLD will need to be configured :\n> sudo update-exim4.conf\n> sudo /etc/init.d/exim4 restart\n> exim -bt $SITE-discuss@list.$SITE$TLD\nThe output from the last command should show 'router = mailman_router, transport = mailman_transport'"
			else
				echo " - Done confirming Exim4 configured correctly"
			fi # End checking if Exim4 can route to the mailing list domain correctly
		fi # End checking if Exim4 installed

		#CONFIG_INFO="$CONFIG_INFO\n#----- [MAILMAN : EXIM4 CONFIG] -----#\n[Warn] Have not coded this part yet. Did not edit the exim4 config files\n[Notice] If you would like to run mailman edit the Exim4 configuration files using the following commands :\n> nano /etc/exim4/update-exim4.conf.conf # Add list.$SITE$TLD to 'dc_other_hostnames'\n> nano /etc/exim4/conf.d/main/04_exim4-config_mailman # Add list.$SITE$TLD to 'domainlist mm_domains'\n> update-exim4.conf\n> nano /etc/init.d/exim4 restart\n> exim -bt testing-announce@list.$SITE$TLD  # Confirm the routing is via mailman"
	fi # End checking if the newlist command exists


	## Add the Mailman info to the Apache site configuration file ##
	touch /etc/apache2/sites-available/$SITE
	cat >> /etc/apache2/sites-available/$SITE <<END-of-CONFIG
	
#########################
###  list.$SITE  ####
#########################
# Note : This is for the Mailman mailing list(s)
<Virtualhost *:80>
    ServerAdmin contact@$SITE$TLD
    ServerName list.$SITE$TLD
    ServerAlias $(site_aliases list.)
    ServerSignature On

    DocumentRoot /var/www/$SITE/list/
    CustomLog /var/log/apache2/$SITE/list.$SITE.log vhost_combined
    ErrorLog /var/log/apache2/$SITE/error.log

    ## Redirects to the mailman list info page.
    RedirectMatch ^/$ /mailman/listinfo/
    Options Indexes FollowSymLinks MultiViews

# Mailman #
    ScriptAlias /cgi-bin/mailman/ /usr/lib/cgi-bin/mailman/
    Alias /pipermail/ /var/lib/mailman/archives/public/
    Alias /images/mailman/ /usr/share/images/mailman/
    ScriptAlias /mailman/ /usr/lib/cgi-bin/mailman/
    <Directory /usr/lib/cgi-bin/mailman/>
        AllowOverride None
        Options ExecCGI
        AddHandler cgi-script .cgi
        Order allow,deny
        Allow from all
    </Directory>
    <Directory /var/lib/mailman/archives/public/>
        Options Indexes FollowSymlinks
        AllowOverride None
        Order allow,deny
        Allow from all
    </Directory>
    <Directory /usr/share/images/mailman/>
        AllowOverride None
        Order allow,deny
        Allow from all
    </Directory>
</Virtualhost>
END-of-CONFIG
echo " - Done installing and configuring the Mailman mailing list, including Exim4 and Apache Site"
fi # End Mailman config install
#--------------------------------------------------------------------------------------------#













########################
## APACHE SITE CONFIG ##
########################
#======================================================================#
echo "# Apache #"
echo "[Note] Now processing Apache site file creation"

touch /etc/apache2/sites-available/$SITE
cat >> /etc/apache2/sites-available/$SITE <<END-of-CONFIG

#################################
####  staging.$SITE$TLD  ####
#################################
<Virtualhost *:80>
        ServerAdmin contact@$SITE$TLD
        ServerName staging.$SITE$TLD
		ServerAlias $(site_aliases staging.)

        DocumentRoot /var/www/$SITE/staging/www
        CustomLog /var/log/apache2/$SITE/staging.$SITE.log vhost_combined
        ErrorLog /var/log/apache2/$SITE/error.log
        ServerSignature On

        <Directory '/var/www/$SITE/staging/www'>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride All
            Order allow,deny
            Allow from all
        </Directory>
</Virtualhost>



# PRIMARY CONFIG #
#########################
####  $SITE$TLD  ####
#########################
<Virtualhost *:80>
        ServerAdmin contact@$SITE$TLD
        ServerName www.$SITE$TLD
		ServerAlias $(site_aliases www.)
		ServerAlias $(site_aliases)
		ServerAlias $(site_aliases *.)
        ServerSignature On

        DocumentRoot /var/www/$SITE/www/
        CustomLog /var/log/apache2/$SITE/www.$SITE.log vhost_combined
        ErrorLog /var/log/apache2/$SITE/error.log

        Options Indexes FollowSymLinks MultiViews
        #RedirectMatch ^/$ /wp/
</Virtualhost>
END-of-CONFIG

if [ -f /etc/apache2/sites-available/$SITE ]; then
	a2ensite $SITE
	/etc/init.d/apache2 reload
	echo " - Done configuring Apache Site"
else
	CONFIG_INFO="$CONFIG_INFO\n#----- [APACHE : CONFIG ERROR] -----#\n[Error] Unable to create Apache config file /etc/apache2/sites-available/$SITE\n[Warn] Please create the config file and enable the site using :\n> sudo nano /etc/apache2/sites-available/$SITE\nsudo a2ensite $SITE\n"
fi # End enabling the Apache site

## Add the .htaccess redirect to primary site domain ##
cat >> /var/www/$SITE/www/.htaccess <<END-of-CONFIG
## Created by create_site.sh script on $CURRENT_DATE to redirect anyone to www.$SITE$TLD.
Options +FollowSymLinks 
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.$SITE$TLD [NC]
RewriteRule ^(.*)$ http://www.$SITE$TLD/$1 [R=301,L]
END-of-CONFIG

if [ -f  /var/www/$SITE/www/.htaccess ]; then
	chown www-data:www-data -R /var/www/$SITE/www/.htaccess # Change it to be owned by the apache web user
	echo " - Done configuring the .htaccess file"
else
	echo "[Error] Unable to create /var/www/$SITE/www/.htaccess file"
	CONFIG_INFO="$CONFIG_INFO\n#----- [APACHE : .HTACCESS ERROR] -----#\n[Error] Unable to create .htaccess file at /var/www/$SITE/www/.htaccess\n[Warn] The site will not have any redirects in place and will be accessible via both http://www.$SITE$TLD and http://$SITE$TLD"
fi # End checking the .htaccess file was added correctly



echo '----------------------------------------------'
echo '- Done Processing'
echo ""
echo "  Note this script makes certain site config assumptions if you wish to edit the Apache site file run the following :"
echo ""
echo " > sudo nano /etc/apache2/sites-available/$SITE"
echo " > sudo /etc/init.d/apache2 reload"
echo " ------- "
echo "Don't forget to setup Google Analytics http://www.google.com/analytics/, or webalizer, etc.."
CONFIG_INFO="$CONFIG_INFO\n########### DON'T FORGET ###########\n # Setup DNS hosting\n # Setup Google Analytics http://www.google.com/analytics/\n # Setup Webalizer (if required)\n # Check that the site works!\n#---- Thank you for creating $SITE ---#\n"
echo " ------- "

echo <<TO-REMOVE-IT

### HOW TO REMOVE ###
If you would like to undo most of the creation script here's where to start :
# Remove the web files
sudo rm -Rv /var/www/$SITE/
sudo rm -Rv /var/www/$SITE/.ht*
# Remove the mailman lists (Note : -a removes the archives as well)
sudo rmlist -a $SITE-discuss
sudo rmlist -a $SITE-announce

# FTP User account details
sudo rm -Rv /home/ftpusers/$SITE/
sudo pure-pw userdel $SITE -m

## Suggest using php-myadmin to remove the MySQL $SITE user and $SITE database ##
# If you need to remove the MySQL db and user by hand run the following into mysql :
DROP USER 'testing'@'localhost';
DROP DATABASE IF EXISTS `testing` ;
#####################
TO-REMOVE-IT

## To add 
# Option to add the Mailman  mailing list (and try to add the Exim4 config) if requested
# Ability to append an ANAT subdomain to the main list (and make a backup copy of the apache sites file)
# Option to output instructions if the ANAT subdomain should be added to the main blog.anat.org.au WordPress Multi-site hosting.
# Ability to check the site works (curl? wget?). If not, a suggestion to ensure the DNS is set, etc..
# ADD TO LINKLINT ARRAY! (Will need to get it to access an external file, and will need to SSH into the appropriate machine and run a .sh script which adds the domain to the file
# Make better passwords. Maybe use a dictionary?
## Reminder to self. When creating a new server, check that the FTPuser is added to the www-data group and that the www-data user is added to the FTPgroup, plus the anat  user is added to both groups (once off per server)



## Just double check the expect file is removed as it contains ftp password info ##
if [ -f temp_expect_file.temp ]; then
	rm temp_expect_file.temp
fi # End double check removal of temp files


#### DONE! Now output the config info and email it ####
echo
echo
echo
echo "==============================================="
echo "==============================================="
echo "============= Configuration Info =============="
echo "==============================================="
echo "==============================================="
echo -e $CONFIG_INFO

if [ "$EMAIL" != "" ]; then 
	echo -e $CONFIG_INFO | mail -s "[Create_Site] $SITE$TLD configuration information : $CURRENTDATE" $EMAIL
fi # End emailing the user

exit

##############
## FINISHED ##
##############
