#!/bin/dash
# Run busybox ntpd once, to sync time from the Internet at boot
# Description: Set local time from Internet time servers at boot. Either run this or run ntpd-client, not both.
# $1 - start, stop, restart, status
SERVER=pool.ntp.org
UP_FLAG=/tmp/60-ntpd-boot
TIMEOUT=30

HWCLOCKPARM="--localtime" # default
HWCLOCKCONF=/etc/hwclock.conf
[ -e $HWCLOCKCONF ] && . $HWCLOCKCONF

wait_for_network() {
	while [ $TIMEOUT -ge 0 ]; do
		nslookup $SERVER 2>/dev/null 1>&2 && return
		sleep 1
		: $((TIMEOUT=TIMEOUT-1))
	done
}

stop() {
	if [ -f $UP_FLAG ]; then
		kill $(cat $UP_FLAG)
		rm -f $UP_FLAG
	fi
}

start() {
	wait_for_network
	ntpd -nqp $SERVER
	hwclock --systohc $HWCLOCKPARM $HWCLOCKRTC
	rm -f $UP_FLAG
}

case $1 in
	start|restart)
		stop; sleep 1; start &
		echo $! > $UP_FLAG
		;;
		
	stop)
		stop
		;;
	
	status) 
		[ -e $UP_FLAG ] && echo "ntpd-boot is running." || echo "ntpd-boot is stopped." 
		;;
		
esac
