#!/bin/dash
# Run busybox ntpd to keep time always sync-ed to Internet time servers.
# Description: Run ntpd to automatically keep time in sync. Either run this or run ntpd-boot, not both.
# $1 - start, stop, restart, status
SERVER=pool.ntp.org
SCRIPT=/usr/share/bbscript/ntp.script
TIMEOUT=30

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

stop() {
	killall ntpd
}

start() {
	if ! pidof ntpd > /dev/null; then
		wait_for_network
		ntpd -S $SCRIPT -p $SERVER 
	fi
}

case $1 in
	start|restart) 
		stop; sleep 1; start &
		;;
		
	stop) 
		stop
		;;
		
	status) 
		pidof ntpd >/dev/null && echo "ntpd-client is running." || echo "ntpd-client is stopped." 
		;;
esac
