#!/bin/sh

. /lib/functions.sh

update_interface()  {
	local section="$1"
	local ifname
	local sec_type
	local count

	ifname="$(uci_get network "$section" "ifname")"
	sec_type="$(uci_get network "$section" "type")"

	if [ -n "$ifname" ]; then
		uci_remove "network" "$section" "ifname"
	else
		return
	fi

	[ -n "$sec_type" ] && uci_remove "network" "$section" "type"

	count=0
	for intf in $ifname; do
		count=$((count+1))
	done

	if [ "$count" -gt 1 ] || [ "$sec_type" = "bridge" ]; then
		uci_add "network" "device" "br_${section}"
		uci_set "network" "br_${section}" "name" "br-${section}"
		uci_set "network" "br_${section}" "type" "bridge"
		for i in $ifname;do
			uci_add_list "network" "br_${section}" "ports" "$i"
		done
		uci_set "network" "$section" "device" "br-${section}"
	else
		uci_set "network" "$section" "device" "$ifname"
	fi
}

config_load "network"
config_foreach update_interface "interface"
uci_commit "network"

exit 0
