#!/bin/bash

echo "Enter a domain. e.g. example.com";
read domain;
echo "Enter a subdomain name. e.g. vhost as in vhost.example.com";
read vhost;

if [[ "${domain}" != "" && "${vhost}" != "" ]]; then
	if [[ ! -e /var/www/${vhost} ]]; then
		mkdir /var/www/${vhost};
	fi
	if [[ ! -e /var/www/${vhost}/htdocs ]]; then
		mkdir /var/www/${vhost}/htdocs;
	fi
	chown -R www-data:www-data /var/www/${vhost};

	if [[ ! -e /etc/apache2/backup ]]; then
		mkdir /etc/apache2/backup;
	fi

	cp /etc/apache2/httpd.conf /etc/apache2/backup/httpd.conf.`date +%s`;

	echo "" >> /etc/apache2/httpd.conf;
	echo "### ${vhost}.${domain}" >> /etc/apache2/httpd.conf;
	echo "<Directory /var/www/${vhost}/htdocs>" >> /etc/apache2/httpd.conf;
	echo "	Options All MultiViews ExecCGI" >> /etc/apache2/httpd.conf;
	echo "	AddHandler cgi-script cgi pl" >> /etc/apache2/httpd.conf;
	echo "	AllowOverride All" >> /etc/apache2/httpd.conf;
	echo "	Order allow,deny" >> /etc/apache2/httpd.conf;
	echo "	Allow from all" >> /etc/apache2/httpd.conf;
	echo "</Directory>" >> /etc/apache2/httpd.conf;
	echo "<VirtualHost *:80>" >> /etc/apache2/httpd.conf;
	echo "	ServerName ${vhost}.${domain}" >> /etc/apache2/httpd.conf;
	echo "	DocumentRoot /var/www/${vhost}/htdocs" >> /etc/apache2/httpd.conf;
	echo "	LogLevel warn" >> /etc/apache2/httpd.conf;
	echo "	CustomLog /var/log/apache2/access.log combined" >> /etc/apache2/httpd.conf;
	echo "</VirtualHost>" >> /etc/apache2/httpd.conf;
	echo "<VirtualHost *:443>" >> /etc/apache2/httpd.conf;
	echo "	ServerName ${vhost}.${domain}" >> /etc/apache2/httpd.conf;
	echo "	DocumentRoot /var/www/${vhost}/htdocs" >> /etc/apache2/httpd.conf;
	echo "	SSLEngine On" >> /etc/apache2/httpd.conf;
	echo "	SSLCertificateFile /etc/apache2/ssl/apache.pem" >> /etc/apache2/httpd.conf;
	echo "	LogLevel warn" >> /etc/apache2/httpd.conf;
	echo "	CustomLog /var/log/apache2/access.log combined" >> /etc/apache2/httpd.conf;
	echo "</VirtualHost>" >> /etc/apache2/httpd.conf;

	echo "The following was added to /etc/apache2/httpd.conf";
	echo "";
	tail -24 /etc/apache2/httpd.conf
	echo "";

	apache2ctl=`which apache2ctl`;

	echo "Would you like to run an apache config test? [y or n]";
	read is_config_test;

	if [[ "${is_config_test}" == "y" ]]; then
		$apache2ctl configtest;
	fi

	echo "Would you like to restart apache now? [y or n]";
	read is_restart;

	if [[ "${is_restart}" == "y" ]]; then
		echo "Restarting...";
		$apache2ctl graceful; 
	fi;

	echo "All done!!!";
fi