#!/bin/sh

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

usage()
{
        cat <<EOF
Usage:
Run this script as:
$0 [default DNS server IP]
Feed zones into script's standard input, one zone per line.
You may optionally specify a custom DNS server IP for each zone, in the same line, e.g.:
zone.com 192.168.1.254
and such custom DNS server IP will have precedence over default DNS server IP, for this zone.
Empty lines are not allowed, zones with undefined DNS server IP are not allowed.
EOF
}

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

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

set -e

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

chroot_dir='/hsphere/local'
zones_dir=$chroot_dir/var/named
ppa_slaves_dir=$chroot_dir/var/named/ppa_slaves
config_file=/etc/named.conf

echo "Making backup of zone indexes"
zones_backup=`mktemp -d $zones_dir.bckXXXXXX`
cp -rp $zones_dir $zones_backup

echo "Making directory $ppa_slaves_dir for zones transferred to PPA"
mkdir -p $ppa_slaves_dir
chown named.named $ppa_slaves_dir
chmod g+w $ppa_slaves_dir

while read zone_name custom_dns_server_ip; do
        echo "Process '$zone_name' zone with '$custom_dns_server_ip' dns ip"
        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 zone $zone_name"
        fi

        zone_num=`perl -e 'use Digest::MD5  qw(md5); ($d1, $d2) =  unpack("I2", md5($ARGV[0])); print $d1 % 23;' $zone_name`
        domain_zone_file=$zones_dir
        domain_zone_file="${domain_zone_file}/zones_$zone_num.conf"
        if grep -q "^zone \"$zone_name\"" $domain_zone_file; then
                sed -i -e "/^zone \"$zone_name\"/d" $domain_zone_file
        else
                echo "WARNING: Zone $zone_name was not served, perhaps you should not forward it?" 1>&2
        fi

        echo "zone \"$zone_name\" { type slave; file \"ppa_slaves/$zone_name\"; masters { $specific_dns_server_ip; }; };" >> $domain_zone_file
        echo "'$zone_name' zone was updated with '$custom_dns_server_ip' master dns"
done

service named restart

exit 0