#!/bin/sh

if [ -f /etc/conf.d/dnscache ]; then
	. /etc/conf.d/dnscache
fi

if [ -z "$UPDATEHINTS" ]; then
	exit 0
fi

cd /etc/dnscache/servers
NEEDRESTART=
ZONES=`ls /etc/dnscache/servers`
for ZONEFILE in $ZONES; do
	# Convert symlinks to copies, so we can update it
	ZONE="$ZONEFILE"
	if [ -L $ZONEFILE ]; then
		DST="`readlink "$ZONEFILE"`"
		cp -f "$DST" "$ZONEFILE"
	fi

	if [ "$ZONE" = "@" ]; then
		ZONE="."
	fi

	if [ "$ZONE" != "." -o "$FORWARDONLY" = "" ]; then
		TMPF=`mktemp -t`
	
		# Refresh zone info
		dnsqr ns $ZONE | awk '/^answer: ./ { print $5 }' | sort -u | xargs dnsip > $TMPF
		if grep -E -q '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' $TMPF; then
			cmp -s $ZONEFILE $TMPF
			if [ "$?" != 0 ]; then
				NEEDRESTART=yes
				cat $TMPF > $ZONEFILE
			fi
		fi
		rm $TMPF
	fi
done

if [ "$NEEDRESTART" ] && /etc/init.d/dnscache --quiet status; then
	/etc/init.d/dnscache --quiet restart
fi

exit 0
