#!/bin/sh

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

usage()
{
	cat <<EOF
Usage:
Run this script as:
$0
Feed subdomain (DNS zone) names into script's standard input, one name per line.
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
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; do
	if [ -z "$zone_name" ]; then
		continue
	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
done

$named_start restart

exit 0

