#!/bin/bash -e
# this adds a new dns domain to /etc/bind/extra, and as the ServerName
# of an existing apache vhost.  you might need to tweak that if you want it
# to be a ServerAlias instead of the ServerName

if [ \! "$#" = 2 ]; then
	. usage "user domain"
fi

user="$1"
domain="$2"
export user domain

cd /etc/bind/extra

if [ -e "db.$domain" ]; then
	. die "/etc/bind/extra/db.$domain already exists"
fi

< db.TEMPLATE perl -pe 's/DOMAIN/$ENV{domain}/g' > "db.$domain"


modify perl -pe '
	/ADD DOMAINS ABOVE HERE/ && print <<End;
zone "$ENV{domain}" {
	type master;
	file "/etc/bind/extra/db.$ENV{domain}";
};

End
	' : /etc/bind/named.conf.local
modify perl -pe '
	if (s/^\tServerName\s+([^\n]+)/\tServerName $ENV{domain}/) {
		$old_server_name = $1;
	} else {
		s/^\tServerAlias\s+([^\n]+)/\tServerAlias www.$ENV{domain} $old_server_name $1/;
	}
' : "/etc/apache2/sites-available/$user"

vhosts_changed

echo "Domain added: $domain for user $user"
echo "Please remember to tell our 2ndary dns master Anibal about this new domain."
echo "Please tell the domain owner to use nameservers ns1.ucm.dev through ns4.ucm.dev."
