#!/bin/bash

VHOSTNAME=$1
TIER=$2 

HTTPDCONF=/etc/httpd/conf/httpd.conf
VHOSTCONFDIR=/etc/httpd/conf.vhosts.d
DEFVHOSTCONFFILE=$VHOSTCONFDIR/00-default-vhost.conf
VHOSTCONFFILE=$VHOSTCONFDIR/$VHOSTNAME.conf
WWWROOT=/srv
DEFVHOSTDOCROOT=$WWWROOT/default/www
VHOSTDOCROOT=$WWWROOT/$VHOSTNAME/www


# Check arguments
if [ "$VHOSTNAME"  = '' ] || [ "$TIER" = '' ]; then # test, string comparison, ||, if/then/fi
	echo "Syntax: $0 VHOSTNAME TIER"
	exit 1 # exit 1
else
	case $TIER in
		1)	VHOSTADMIN='basic_support@example.com'
			;;
		2)	VHOSTADMIN='business_support@example.com'
			;;
		3)	VHOSTADMIN='enterprise_support@example.com'
			;;
		*)	echo "Invalid tier specified."
			exit 1
			;;
	esac
fi

# Create conf dir one time is not already created
if [ ! -d $VHOSTCONFDIR ]; then # test, file evaluation, if/then/fi
	mkdir $VHOSTCONFDIR

	if [ $? -ne 0 ]; then # test, exit code, numeric comparison, if/then/fi
		echo "ERROR: Failed creating $VHOSTCONFDIR."
		exit 1 # exit 1
	fi
fi

# Add include one time for conf dir if not already added
grep -q '^IncludeOptional conf\.vhosts\.d/\*\.conf$' $HTTPDCONF

if [ $? -ne 0 ]; then # test, exit code, numeric comparison, if/then/fi
	# Backup before modifying
	cp -a $HTTPDCONF $HTTPDCONF.backup

	echo "IncludeOptional conf.vhosts.d/*.conf" >> $HTTPDCONF

	if [ $? -ne 0 ]; then # test, exit code, numeric comparison, if/then/fi
		echo "ERROR: Failed adding include directive."
		exit 1 # exit 1
	fi
fi

# Create default vhost one time if not already added
if [ ! -f $DEFVHOSTCONFFILE ]; then
	cat <<DEFCONFEOF > $DEFVHOSTCONFFILE
<VirtualHost _default_:80>
  DocumentRoot $DEFVHOSTDOCROOT
  CustomLog "logs/default-vhost.log" combined
</VirtualHost>

<Directory $DEFVHOSTDOCROOT>
  Require all granted
</Directory>
DEFCONFEOF
fi

if [ ! -d $DEFVHOSTDOCROOT ]; then
        mkdir -p $DEFVHOSTDOCROOT
        restorecon -R $WWWROOT
fi



# Make sure conf file doesn't already exist so we don't accidentally overwrite
if [ -f $VHOSTCONFFILE ]; then # test, file evaluation, if/then/elif/else,fi
	echo "ERROR: $VHOSTCONFFILE already exists."
        exit 1 # exit 1
elif [ -d $VHOSTDOCROOT ]; then # test, file evaluation
	echo "ERROR: $VHOSTDOCROOT already exists."
        exit 1 # exit 1
else 
	cat <<CONFEOF > $VHOSTCONFFILE
<VirtualHost *:80>
  ServerName $VHOSTNAME
  ServerAdmin $VHOSTADMIN
  DocumentRoot $VHOSTDOCROOT
  ErrorLog "logs/${VHOSTNAME}_error_log"
  CustomLog "logs/${VHOSTNAME}_access_log" common
</VirtualHost>

<Directory $VHOSTDOCROOT>
  Require all granted
</Directory>
CONFEOF

        mkdir -p $VHOSTDOCROOT
        restorecon -R $WWWROOT
fi


# Check config and reload
apachectl configtest &> /dev/null

if [ $? -eq 0 ]; then
	systemctl reload httpd &> /dev/null
else
	echo "ERROR: Config error."
	exit 1
fi
