#!/bin/sh

. /lib/functions.sh

management_interfaces() {
	local DHCP_IFACES=""

	is_notbridged_dhcp() {
		local config="$1"
		local proto="$(uci -q get network.$config.proto)"
		local typ="$(uci -q get network.$config.type)"
		if [ "$proto" == "dhcp" -a "$typ" != "bridge" ]; then
			DHCP_IFACES="$DHCP_IFACES $config"
		fi
	}

	config_load network
	config_foreach is_notbridged_dhcp interface
	echo $DHCP_IFACES
}

set_iup_reqopts() {
	### Ask for IUP related DHCP options only if IUP is enabled ###
	new_reqopts() {
		local net=$1
		local enabled="$(uci -q get provisioning.iup.enabled)"
		enabled="${enabled:-on}"
		local newreqopts=
		local baseopts=
		local reqopts="$(uci -q get network.$net.reqopts)"
		local iupopts="66 67 128 224 225 226"
		local ropt iopt
		local net
		for ropt in $reqopts; do
			case $ropt in
				66|67|128|224|225|226) ;;
				*) baseopts="$baseopts $ropt" ;;
			esac
		done
		ropt=""
		reqopts="$baseopts $iupopts"
		for ropt in $reqopts; do
			case $ropt in
				66|67|128|224|225|226) [ $enabled == "on" ] && newreqopts="$newreqopts $ropt" ;;
				*) newreqopts="$newreqopts $ropt" ;;
			esac
		done
		newreqopts="$(echo $newreqopts | tr ' ' '\n' | sort -n | tr '\n' ' ' | sed 's/^[ \t]*//;s/[ \t]*$//')"
		echo "$newreqopts"
	}
	for net in $(management_interfaces); do
		uci -q set network.$net.reqopts="$(new_reqopts $net)"
	done
	uci commit network
}

set_iup_reqopts
