#!/bin/sh

. /lib/functions.sh

get_access_role()
{
	local mode lan_proto

	lan_proto="$(uci -q get network.lan.proto)"

	if [ "${lan_proto}" == "dhcp" ]; then
		mode="extender"
	else
		mode="full_access"
	fi

	echo "$mode"
}

configure_dhcp_options() {
	local enabled inerface discovery
	config_load obuspa
	config_get_bool enabled global enabled 1
	config_get interface global interface
	config_get_bool discovery global dhcp_discovery 1

	if [ "${enabled}" -eq 0 ]; then
		return 0
	fi

	if [ "${discovery}" -eq 0 ]; then
		return 0
	fi

	if [ -z "${interface}" ]; then
		role="$(get_access_role)"

		if [ "${role}" = "extender" ]; then
			interface="lan"
			uci -q set obuspa.global.interface="lan"
		else
			interface="wan"
		fi
	fi

	reqopts="$(uci -q get network."${interface}".reqopts)"
	proto="$(uci -q get network."${interface}".proto)"
	local req125_present=0

	for ropt in $reqopts; do
		case $ropt in
			125) req125_present=1 ;;
			*) ;;
		esac
	done

	sendopts="$(uci -q get network."${interface}".sendopts)"
	opt124="124:"
	send124_present=0
	for sopt in $sendopts; do
		if [[ "$sopt" == "$opt124"* ]]; then
			send124_present=1
			break
		fi
	done

	if [ "${proto}" = "dhcp" ]; then
		if [ ${req125_present} -eq 0 ]; then
			newreqopts="$reqopts 125"
			uci -q set network."${interface}".reqopts="$newreqopts"
		fi

		if [ ${send124_present} -eq 0 ]; then
			newsendopts="${sendopts} 124:00:00:0D:E9:04:03:75:73:70"
			uci -q set network."${interface}".sendopts="$newsendopts"
		fi
	fi
}

configure_dhcp_options
