#!/bin/bash

logger -t named "Refresh named config request"

force=$1

/opt/Eye/scripts/utils/bind/print-dns-zones.pl
[ $? -ne 0 ] && exit 1

RELOAD=
ZONELIST=`ls -x -1 /etc/bind/masters/db.*.new`
echo "${ZONELIST}" | while read NS2_DB; do
NS1_DB=`echo "$NS2_DB" | sed 's/.new$//'`
[ ! -e $NS1_DB ] && {
    cat $NS2_DB > $NS1_DB
    chown bind:bind ${NS1_DB} >/dev/null
    RELOAD=1
    continue
    }
TMP_R1=`mktemp /tmp/rev_old.XXXXXXXXXX`
TMP_R2=`mktemp /tmp/rev_new.XXXXXXXXXX`
S1=`cat $NS1_DB | grep "; serial" | awk '{ print \$1 }'`
S2=`cat $NS2_DB | grep "; serial" | awk '{ print \$1 }'`
cat $NS1_DB | grep -v "; serial" >$TMP_R2
cat $NS2_DB | grep -v "; serial" >$TMP_R1
diff -aqbBfi $TMP_R2 $TMP_R1 >/dev/null
state=$?
rm -f $TMP_R1 >/dev/null
rm -f $TMP_R2 >/dev/null
[ ${state} -eq 0 ] && continue
echo "dns config $NS1_DB changed."
cat $NS2_DB > $NS1_DB
RELOAD=1
rm -f "${NS2_DB}" >/dev/null
chown bind:bind ${NS1_DB} >/dev/null
done

diff -aqbBfi /etc/bind/named.dynamic.new /etc/bind/named.dynamic >/dev/null
[ $? -ne 0 ] && {
    RELOAD=1
    cat /etc/bind/named.dynamic.new >/etc/bind/named.dynamic
    }

if [ -n "${RELOAD}" -o -n "${force}" ]; then
    logger -t named "Configuration changed. Check config"
    /usr/bin/named-checkconf -t / -z >/dev/null
    if [ $? -eq 0 ]; then
        logger -t named "Config fine! Restart named"
        /usr/bin/systemctl restart named >/dev/null
        fi
    else
        logger -t named "Config not changed! Skip restart"
    fi

rm -f /etc/bind/named.dynamic.new 2>/dev/null
rm -f /etc/bind/masters/db.*.new 2>/dev/null

logger -t named "done"

exit
