#!/bin/sh /etc/rc.common
# Copyright (C) 2006-2011 OpenWrt.org

START=19

. /etc/model.config

get_device_index_by_name() {
	ifname=$1
	[ -n "$ifname" ] || return

	dev_index=0
	while [ 1 ]; do
		device_name=`uci get network.@device[$dev_index].name 2>/dev/null`
		[ -n "$device_name" ] || break
		[ "$device_name" == "$ifname" ] && {
			echo $dev_index
			break;
		}
		let 'dev_index+=1'
	done
}

start()
{
	mode=`uci get sysmode.config.mode`
	lanmac=`devinfo show lanMac` || {
		echo "Warning: no MAC address in factory partition" >/dev/console
		return 0
	}
	local suffix=${lanmac:9:9}
	suffix=0x${suffix//:/}
	local v=$((suffix+1))
	wanmac=${lanmac:0:9}`printf "%02X:%02X:%02X" $(((v>>16)&0xff)) $(((v>>8)&0xff)) $((v&0xff))`
	v=$((v+1))
	wanmac_v6=${lanmac:0:9}`printf "%02X:%02X:%02X" $(((v>>16)&0xff)) $(((v>>8)&0xff)) $((v&0xff))`

	need_commit=0
	dev_index=`get_device_index_by_name br-lan`
	oldlanmac=`uci get network.@device[$dev_index].macaddr 2>/dev/null`
	
	# LAN bridge
	if [ "$lanmac" != "$oldlanmac"  -a "$mode" == "0" ]; then 
		uci set network.@device[$dev_index].macaddr="$lanmac"
		need_commit=1
	fi

	if [ "$wanmac" != "$oldlanmc"  -a "$mode" == "1" ]; then
		uci set network.@device[$dev_index].macaddr="$wanmac"
		need_commit=1
	fi


	#WAN
	uci set network.wan.default_mac="$wanmac"
	dev_index=`get_device_index_by_name ${wanif}`
	uci get network.@device[$dev_index].macaddr 2>/dev/null || {
		uci set network.@device[$dev_index].macaddr="$wanmac"
		uci set network.@device[$dev_index].default_mac="$wanmac"
		need_commit=1
	}

	#WAN6
	wanif6=${wanif}-v6
	dev_index=`get_device_index_by_name ${wanif6}`
	uci get network.@device[$dev_index].macaddr 2>/dev/null || {
		uci set network.@device[$dev_index].macaddr="$wanmac_v6"
		need_commit=1
	}

	#VLAN
	vif_index=1
	for lif in $lanvifs; do
		dev_index=`get_device_index_by_name $lif`
		[ -n "$dev_index" ] || continue
		uci get network.@device[$dev_index].macaddr 2>/dev/null || {
			suffix=${lanmac:9:2}
			suffix=0x${suffix}
			v=$((suffix+vif_index))
			vlan_addr=${lanmac:0:9}`printf "%02x" $((v&0xff))`${lanmac:11:6}
			let 'vif_index+=1'
			uci set network.@device[$dev_index].macaddr="$vlan_addr"
			need_commit=1
		}
		let 'dev_index+=1'
	done

	[ $need_commit -eq 0 ] || uci commit network
}

