#!/bin/sh

ntp_service=/etc/init.d/sysntpd
ntp_pid=

restart_ntp_service() {
	[ -x "$ntp_service" ] || return 0
	"$ntp_service" restart >/dev/null 2>&1 || true
}

cleanup() {
	if [ -n "$ntp_pid" ]; then
		kill "$ntp_pid" 2>/dev/null || true
		wait "$ntp_pid" 2>/dev/null || true
	fi
	restart_ntp_service
}

trap cleanup EXIT
trap 'exit 1' HUP INT TERM

[ -x "$ntp_service" ] || {
	echo "error: sysntpd service is unavailable" >&2
	exit 1
}
command -v ntpd >/dev/null 2>&1 || {
	echo "error: ntpd is unavailable" >&2
	exit 1
}

"$ntp_service" stop >/dev/null 2>&1 || {
	echo "error: could not stop sysntpd for one-shot synchronization" >&2
	exit 1
}

# Use Cloudflare's documented IPv6 and IPv4 NTP addresses so initial clock
# recovery does not depend on DNS or on one address family being usable.
ntpd -n -q \
	-p 2606:4700:f1::123 \
	-p 162.159.200.123 \
	>/dev/null 2>&1 &
ntp_pid=$!

elapsed=0
while kill -0 "$ntp_pid" 2>/dev/null; do
	if [ "$elapsed" -ge 30 ]; then
		kill -TERM "$ntp_pid" 2>/dev/null || true
		sleep 2
		kill -KILL "$ntp_pid" 2>/dev/null || true
		break
	fi
	sleep 1
	elapsed=$((elapsed + 1))
done

if wait "$ntp_pid"; then
	ntp_status=0
else
	ntp_status=$?
fi
ntp_pid=

if [ "$ntp_status" -ne 0 ]; then
	echo "error: one-shot NTP synchronization failed" >&2
	exit 1
fi

echo "Auto-IPoE system time synchronized"
exit 0
