#!/bin/sh
# Copyright (C) 2006 OpenWrt.org

now=$(cat /proc/uptime | awk 'FS="[.]+" {print $1}')
runtime=$(uci -q -P /var/state get network.ifup_running 2>/dev/null)
if [ $now -ge 100 -a $1 = "wan" -a -n "$runtime" ]; then
	DIFF=$(($now - $runtime))
	if [ $DIFF -le 30 ]; then
		logger "ifup is running.......skip ifup $1"
		return
	else
		uci revert -P /var/state/ network.ifup_running
	fi
fi

. /sbin/ifdown "$@"

if [ $1 = "wan" ]; then
	uci -q -P /var/state set network.ifup_running=$now	# revert this when wan.up=1
fi

config_get iftype "$1" type
config_get ifname "$1" device

for dev in $ifname; do
	setup_interface "$dev" "$1"
done

# for fiber WAN
phy_type=$(uci -q get network.wan_phy_type -P /var/state || echo "8601")
if [ "$phy_type" == "8211" ]; then
    echo "write 1 5 0x0 0x103f4181" | armio
fi

#. /sbin/flush-ipconntrack 15 &
#en_ipsec=$(uci -c /etc/config/grocx/ get vtss_fw.@basic[0].enable_vpn)
#if [ $en_ipsec = "1" -a $1 = "wan" -a -f /var/run/pluto/ipsec.info ]; then 
#	/etc/init.d/ipsec restart
#fi

#ipv6 setting
if [ $1 == "wan" ]; then
	echo "IPv6 WAN up"
	WAN_MODE=$(uci -q get ipv6.wan.mode)
	if [ $WAN_MODE == "dhcpv6" ]; then
		/usr/sbin/dhcpv6_client.sh
	elif [ $WAN_MODE == "static" ]; then
		/usr/sbin/ipv6_wan_static.sh
	fi
elif [ $1 == "lan" ]; then
	
	#set autoconfig
	LAN_AUTO=$(uci -q get ipv6.lan.autoconfig)
	LAN_MODE=$(uci -q get ipv6.lan.mode)
	if [ $LAN_AUTO == "1" ]; then
		echo "IPv6 LAN up"
		if [ $LAN_MODE == "dhcpv6" ]; then
			/usr/sbin/dhcpv6_server.sh
		fi
		if [ $LAN_MODE == "radvd" ]; then
			/usr/sbin/radvd.sh
		fi
	fi
	
	#set LAN IPv6 IP
	LAN_IPv6=$(uci -q get ipv6.lan.global_addr)
	if [ $LAN_IPv6 ]; then
		ifconfig eth0 $LAN_IPv6/64 
	fi
fi

/lib/firewall6.sh start
/lib/remote_mgr6.sh start