#!/bin/sh

. /lib/functions.sh

next_sid() {
	is_integer() {
		case "$1" in
			''|*[!0-9]*)
				return 1
				;;
			*)
				return 0
				;;
		esac
	}

	handle_section() {
		local sid="$1"

		if is_integer "$sid" && [ "$sid" -ge "$next_sid" ]; then
			next_sid=$(( sid + 1 ))
		fi
	}

	local next_sid=1

	config_load ntpd
	config_foreach handle_section

	echo "$next_sid"
}

handle_server() {
	local value="$1"
	local sid="$(next_sid)"

	uci_add ntpd ntp_server "$sid"
	uci_set ntpd "$sid" host "$value"
}

config_load ntpd
config_list_foreach ntp server handle_server

uci_remove ntpd ntp server 2>/dev/null
uci_commit ntpd

exit 0
