IFACE_GLOBAL=$(uci_get "system.@rdate[0].interface")
SERVERS=
MAX=0
SYNCED=

do_rdate()
{
	local server="$1"

	rdate -s "$server" >/dev/null 2>/dev/null && {
		logger -t rdate "Synced with $server"
		SYNCED="$server"
	} || {
		logger -t rdate "Failed to sync with $server"
	}
}

add_server()
{
	local section="$1"

	local server
	config_get server "$section" hostname
	[ -z "$server" ] && return

	local iface
	config_get iface "$section" interface
	[ -z "$iface" ] && iface=$IFACE_GLOBAL
	[ -n "$iface" ] && {
		[ "$iface" = "$INTERFACE" ] || return
	}

	SERVERS="${SERVERS} $server"; : $((MAX++))
}

sync_time()
{
	local server
	server=$(uci_get_state "network.$INTERFACE.lease_timesrv")
	[ -n "$server" ] && do_rdate "$server"
	[ -n "$SYNCED" ] && return

	config_load timeserver
	config_foreach add_server timeserver

	local servers
	while [ $MAX -gt 0 ] && [ -z "$SYNCED" ]; do
		unset servers; random=$(awk "BEGIN { srand(); print int(rand() * $MAX + 1); }")
		for server in $SERVERS; do
			[ $((--random)) -eq 0 ] && { do_rdate "$server"; continue; }
			servers="${servers} $server"
		done
		SERVERS="${servers}"; : $((MAX--))
	done

	[ -z "$SYNCED" ] && logger -t rdate "No usable time server for $INTERFACE found"
}

case "${ACTION:-ifup}" in
	ifup)
		sync_time
	;;
esac