#!/bin/sh

. /lib/functions.sh
. /usr/share/libubox/jshn.sh

source "/etc/device_info"

l3_mcast_config() {
	# configure L3 mcast config
	logger -s -p user.info -t "netmode" "Generating L3 mcast configuration"

	rm -f /etc/config/mcast
	sh /rom/etc/uci-defaults/61-mcast_config_generate
	uci -q commit mcast
}

l3_network_config() {
	logger -s -p user.info -t "netmode" "Generating L3 network configuration"

	# Configure L3 Network Mode
	uci -q set network.lan=interface
	uci -q set network.lan.device='br-lan'
	uci -q set network.lan.proto='static'
	uci -q set network.lan.ipaddr='192.168.1.1'
	uci -q set network.lan.netmask='255.255.255.0'
	uci -q set network.lan.ip6assign='60'
	uci -q delete network.lan.vendorid
	uci -q delete network.lan.clientid
	uci -q delete network.lan.reqopts
	uci -q delete network.lan.sendopts

	uci -q delete network.lan6	

	uci -q set network.wan=interface
	uci -q set network.wan.proto='dhcp'
	uci -q delete network.wan.disabled
	uci -q delete network.wan.username
	uci -q delete network.wan.password

	uci -q set network.wan6=interface
	uci -q set network.wan6.proto='dhcpv6'
	uci -q delete network.wan6.disabled

	uci -q delete network.br_lan.ports
	uci -q set network.br_lan.bridge_empty='1'

	add_port_to_br_lan() {
		port="$1"
		[ -n "$port" -a -d /sys/class/net/$port ] || continue
		uci add_list network.br_lan.ports="$port"
	}

	if [ -f /etc/board.json ]; then
		json_load_file /etc/board.json
		json_select network
		json_select lan
		if json_is_a ports array; then
			json_for_each_item add_port_to_br_lan ports
		else
			json_get_var device device
			[ -n "$device" ] && uci add_list network.br_lan.ports="$device"
		fi
		json_select ..
		json_select wan 2>/dev/null
		json_get_var device device
		if [ -n "$device" ]; then
			uci -q set network.wan.device="$device"
			uci -q set network.wan6.device="$device"
		fi
		json_cleanup
	fi

	uci -q commit network

	# Enable DHCP Server
	uci -q set dhcp.lan.ignore=0
	uci -q set dhcp.wan.ignore=1
	uci -q commit dhcp
	/etc/init.d/odhcpd enable

	# Enable SSDPD
	uci -q set ssdpd.ssdp.enabled="1"
	uci -q commit ssdpd

	# Update CWMP Agent WAN Interface
	uci -q set cwmp.cpe.default_wan_interface="wan"
	uci -q commit cwmp

	# Update gateway WAN Interface
	uci -q set gateway.global.wan_interface="wan"
	uci -q commit gateway

	# Enable firewall
	uci -q set firewall.globals.enabled="1"
	uci -q commit firewall
}

l3_network_config
l3_mcast_config

# If device is already boot-up, assume netmode changed during runtime
if [ -f /var/run/boot_complete ]; then
	/etc/init.d/odhcpd restart 2>/dev/null
	for config in network dhcp ssdpd cwmp gateway firewall mcast; do
		ubus call uci commit "{\"config\":\"$config\"}"
		sleep 1
	done
fi
