#!/bin/sh
#
# fetchroots.cron  - fetch the root servers cache file
#
# Maintainer: Phillip Smith <fukawi2@archserver.org>
# Contributor: Steven Lynch <sl@ieee.org>

# comment this out if not using a proxy server
# export ftp_proxy="proxy:3128"

fname=`/usr/bin/mktemp`
URL="ftp://ftp.rs.internic.net/domain/named.root"
log="/var/log/fetchroots.log"
namedir="/var/named"
dname="root.hint"
USER_ID='named'
GROUP_ID='named'

usage() {
	echo "Usage: $0 [-q] [-g]"
	echo "  -q   Be quiet!"
	echo "  -g   Use git (commit any changes)"
}

# cmd line options
VERBOSE=true
GIT=false
while (( "$#" )); do
	OPT=$1
	shift
	
	case "$OPT" in
	-q)
		VERBOSE=false
		;;
	-g)
		GIT=true
		;;
	*)
		usage
		exit 1
		;;
	esac
done

# go get the latest file
cd $namedir

/usr/bin/wget -S -o $log -O $fname $URL
if [ $? -eq 0 -a -s $fname ] ; then
	# check if we need to replace the existing file
	/usr/bin/cmp -s $fname $dname
	if [ $? -ne 0 ] ; then
		# OK, replace it (keep the old) and reload the nameserver
		/bin/cp -f $dname ${dname}.old
		/bin/mv -f $fname $dname
		/bin/chown $USER_ID:$GROUP_ID $dname
		/bin/chmod 644 $dname
		/bin/chown $USER_ID:$GROUP_ID $dname.old
		/bin/chmod 444 $dname.old
		/usr/sbin/rndc reload
		
		# Commit to git if required
		if [ $GIT ] ; then
			/usr/bin/git commit $dname $dname.old -m 'automatic update by fetchroots' || echo "[ERROR] FAILED TO COMMIT CHANGES TO GIT"
		fi
		
		[ $VERBOSE ] && echo 
		[ $VERBOSE ] && echo "Root servers cache file UPDATED"
	else
		[ $VERBOSE ] && echo 
		[ $VERBOSE ] && echo "Root servers cache file still OK"
	fi
else
	# output the error log so that cron sends mail
	[ $VERBOSE ] && echo
	[ $VERBOSE ] && echo "ERROR downloading root servers cache file"
	[ $VERBOSE ] && echo
	[ $VERBOSE ] && /bin/cat $log
	exit 1
fi

/bin/rm -f $fname

exit 0
