#!/bin/sh

PATH=/usr/sbin:/usr/bin:/bin
TIMEOUT=30
KEY=State:/Network/Global/DNS
DNS=/var/run/resolv.conf
# sentinel to special case DNS readiness at boot
LOG=/var/run/sntp.log

ipconfig waitall

if [[ ! -f ${LOG} ]]; then
    DEADLINE=$((SECONDS+TIMEOUT))
    for (( CURTIMEOUT=TIMEOUT; SECONDS < DEADLINE; CURTIMEOUT=DEADLINE-SECONDS )); do
	if scutil -w ${KEY} -t ${CURTIMEOUT}; then
	    if [[ -f ${DNS} ]]; then 
			break;
	    fi			# else retry false alarms
	else
	    logger -p daemon.err "$0: scutil key ${KEY} not present after ${TIMEOUT} seconds"
	    break;
	fi
    done
fi

for server in $(awk '/^server/ {print $2}' /etc/ntp.conf); do
    if sntp -K /dev/null -S ${server} &> ${LOG}; then
	break
    else
	logger -p daemon.err -f ${LOG}
    fi
done

exec /usr/sbin/ntpd -c /private/etc/ntp-restrict.conf -n -g -p /var/run/ntpd.pid -f /var/db/ntp.drift
