#!/bin/sh

############################# service functions ############################

usage()
{
	cat <<EOF
Usage:
Run this script as:
$0 [default DNS server IP]
Feed subdomain names into script's standard input, one name per line.
You may optionally specify a custom DNS server IP for each subdomain name, in the same line, e.g.:
subdomain.domain.com 192.168.1.254
and such custom DNS server IP will have precedence over default DNS server IP, for this subdomain.
Subdomains with undefined DNS server IP are not allowed.
International subdomain names must be fed in IDN-encoded form.
EOF
}

die()
{
	if [ "$@" ]; then
		echo $@ 1>&2
	fi
	exit 1
}

# get first word of given parameter's value
get_conf_parameter()
{
	local param_name=$1
	if [ ! -e $DNSCONTROLLER_CONF ]; then
		die "DNS controller configuration file $DNSCONTROLLER_CONF is not found"
	fi
	local pattern="^[ \t]*$param_name[ \t]*=[ \t]*\([^ \t#]\+\).*$"
	cat $DNSCONTROLLER_CONF | sed -n "s/$pattern/\\1/p" | tail -1
}

############################### main #############################

DNSCONTROLLER_CONF=/usr/local/dnscontroller/conf/dnscontroller.conf	# this path does not vary
set -e

case "$1" in
-h)	usage
	exit 0
	;;
*)	dns_server_ip=$1
	;;
esac

chroot_dir=`get_conf_parameter chroot_dir`
if [ -f "/etc/SuSE-release" ]; then
	data_dir=$chroot_dir
else
	data_dir=$chroot_dir/var/named
fi

named_start=`get_conf_parameter named_start`
if [ -z "$named_start" ]; then
	echo "Refuse to change the zones: can't determine how to restart 'named' service - 'named_start' parameter is not set in dnscontroller.conf file" 1>&2
	exit 1;
fi

slave_zones_file=$data_dir/slave_zones
ppa_slaves_dir=$data_dir/ppa_slaves
config_file=$chroot_dir/etc/named.conf

echo "Making backup of slave zones index"
slave_zones_backup=`mktemp $slave_zones_file.bckXXXXXX`
cp -p $slave_zones_file $slave_zones_backup

while read zone_name custom_dns_server_ip; do
	if [ -z "$zone_name" ]; then
		continue
	fi

	specific_dns_server_ip=$dns_server_ip
	if [ "$custom_dns_server_ip" ]; then
		specific_dns_server_ip=$custom_dns_server_ip
	fi

	# TBD: if to check is_ip($ip) or even is_reachable($ip), or not at all
	# currently only checking if it's defined
	if [ -z "$specific_dns_server_ip" ]; then
		die "DNS server IP is not set for subdomain $zone_name"
	fi

	if grep -q "^zone \"$zone_name\" {" $slave_zones_file; then
		sed -i "/^zone \"$zone_name\" {$/,/^};/d" $slave_zones_file	# our zones after dnscontroller reformats them
		sed -i "/^zone \"$zone_name\" {.*};$/d" $slave_zones_file	# our zones not reformatted
	fi

	echo "zone \"$zone_name\" { type slave; file \"slaves/$zone_name\"; masters { $specific_dns_server_ip; }; };" >> $slave_zones_file
done

$named_start restart

exit 0

