#!/bin/sh
# Antonio Ávila for Fon Technology (GPL)
#

crontab_file="/etc/crontabs/root"
ntp_file="/etc/config/ntpservers"


config_ntpserver()
{
	verify="false"
	while [ "$verify" != "true" ]
	do
		#Kill them all!
		killall ntpclient
		#Flush previous ntp servers...
		cat /etc/crontabs/root | grep -v ntp > /etc/crontabs/root
		randline=$(expr `head -c1 /dev/urandom | hexdump -d | sed 's/\ //g' | sed 's/^0*//' | head -n1` % `wc -l $ntp_file | sed 's/^\ [ \t]*//' | cut -d" " -f1` + 1)	
		ntpserver=$(head -n$randline $ntp_file | tail -n1)	
	        randminute=$(expr `head -c2 /dev/urandom | hexdump -d | sed 's/\ //g' | sed 's/^0*//' | head -n1` % 60)
	        randhour=$(expr `head -c2 /dev/urandom | hexdump -d | sed 's/\ //g' | sed 's/^0*//' | head -n1` % 24)
	        ntpclient -s -h $ntpserver &
		sleep 5
		
		if [ "`date +%Y`" != "2000" ]
		then
			verify="true"
		fi
	done

        echo "$randminute $randhour * * * ntpclient -s -h $ntpserver" >> $crontab_file
        crontab -l

}
	
	case "$1" in
		"start")
			config_ntpserver&
			;;
		"stop")
			cat $crontab_file | grep -v "ntp" > $crontab_file
			crontab -l
			return
			;;
		*)
			echo "Usage: /etc/init.d/$NAME {start|stop}"
	                exit 1
			;;
	esac
	
