#!/bin/sh

. /lib/functions.sh
. /usr/lib/eth-encap/eth_encap.sh

local config_changed="0"

delete_br_wan_device() {
	local sec_name="$1"
	local id=""
	id="$(uci get network.vlan.id)"
	config_get name "$1" name
	if [ "$name" == "br-wan.""$id" ];then
		uci delete network."$sec_name"
		config_changed="1"
	fi
}

create_wanif(){
    local id=""
    local macaddr=""
    local sec=""
    id="$(uci get network_sync.vlan.id)"
    macaddr="$(uci get network.wan.macaddr)"
    sec="$(uci add network device)"

    uci set network."$sec".enabled="1"
    uci set network."$sec".name="br-wan.""$id"
    uci set network."$sec".macaddr="$macaddr"
    config_changed="1"
}


[ "$POINT" == "END" ] || exit 0;

config_load network

vlan10_detect=$(uci -c /etc/profile.d get profile.vlan10_detect.support)
is_vlan_enable=$(uci -c /etc/config get network.vlan.enable)

if [ "$SRCMODE" = "NONE" -o "$SRCMODE" = "RE" ] && [ "$DSTMODE" = "FAP" -o "$DSTMODE" = "HAP" ]; then
    static_route_set="$(uci get network_sync.@route[0].key)"
    data="$(uci get network_sync.wan.ipaddr)"
    olddata="$(uci get network.wan.ipaddr)"
    if [ -n "$data" ] && [ "$data" != "$olddata" ] || [ -n "$static_route_set" ]; then
        #uci set network.wan.ipaddr="$data"
        config_changed="1"
    fi

    if [ -n "$vlan10_detect" ] && [ "$vlan10_detect" = "yes" ] && [ "$is_vlan_enable" = "0" ]; then
        vlan_add br-wan 10
        ifconfig br-wan.10 up
    fi    
elif [ "$SRCMODE" = "NONE" -o "$SRCMODE" = "FAP" -o "$SRCMODE" = "HAP" ] && [ "$DSTMODE" = "RE" ]; then
    static_route_set="$(uci get network_sync.@route[0].key)"
    data="$(uci get network.wan.ipaddr)"
	[ -n "$data" -o -n "$static_route_set" ] && {
        #uci delete network.wan.ipaddr
        config_changed="1"
    }
    config_foreach delete_br_wan_device device

    if [ -n "$vlan10_detect" ] && [ "$vlan10_detect" = "yes" ] && [ "$is_vlan_enable" = "0" ]; then
        ifconfig br-wan.10 down
        vlan_del br-wan 10
    fi
fi

if [ "$config_changed" = "1" ]; then
    local isMobile=$(isMobile 2>/dev/null)
    local mode=$(uci get sysmode.sysmode.mode)
    local binded=$(cat /tmp/is_binded)

    if [ "$isMobile" = "yes" ] && [ "$mode" = "Router" ] && [ "$binded" = "1" ]; then
        return
    else
        uci commit network
        /etc/init.d/network reload
    fi
fi

