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

logger -p 160.5 "********** ifup $1"

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

. /sbin/ifdown "$@"


uci -q -P /var/state set network.$1.ifup_running=$now	# revert this when wan.up=1

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
WAN_MODE=$(uci -q get ipv6.wan.mode)
if [ $1 == "wan" ]; then
	#echo "IPv6 WAN up"
	if [ $WAN_MODE == "dhcpv6" ]; then
		/usr/sbin/dhcpv6_client.sh
	elif [ $WAN_MODE == "static" ]; then
		/usr/sbin/ipv6_wan_static.sh
	elif [ $WAN_MODE == "dhcpv6-3" -o $WAN_MODE == "dhcpv6-4" ]; then
		LAN_STATIC_IPv6=$(uci -q get ipv6.lan.global_addr | tr A-Z a-z)
		if [ $LAN_STATIC_IPv6 ]; then
			LAN_IPv6=$(ifconfig br-lan | grep "inet6 addr" | grep -v -E "fe80::|/128" | grep -v "$LAN_STATIC_IPv6" | sed -e "s/^.*inet6 addr: //" -e "s/ Scope.*\$//")
		else
			LAN_IPv6=$(ifconfig br-lan | grep "inet6 addr" | grep -v -E "fe80::|/128" | sed -e "s/^.*inet6 addr: //" -e "s/ Scope.*\$//")
		fi
		ifconfig br-lan del $LAN_IPv6
		if [ $WAN_MODE == "dhcpv6-3" ]; then
			/sbin/dhcp6.sh client start iapd 2>&1
		else
			/sbin/dhcp6.sh client start both 2>&1
		fi
	fi
elif [ $1 == "lan" ]; then
	
	#set autoconfig
	LAN_AUTO=$(uci -q get ipv6.lan.autoconfig)
	RADVD_EN=$(uci -q get ipv6.lan.radvd_en)
	DHCP6_EN=$(uci -q get ipv6.lan.dhcp6_en)
	
	#step 1. killall IPv6 LAN application
	killall -q wide-dhcp6s
	killall -q radvd

	#echo "IPv6 LAN up"
	if [ "$RADVD_EN" == "1" ]; then
		/usr/sbin/radvd.sh
	fi
	if [ "$DHCP6_EN" == "1" ]; then
		/usr/sbin/dhcpv6_server.sh
	fi
	
	#set LAN IPv6 IP
	LAN_IPv6=$(uci -q get ipv6.lan.global_addr)
	if [ $LAN_IPv6 ]; then
		#ifconfig eth0 $LAN_IPv6/64			#by Sleer
		ifconfig br-lan $LAN_IPv6/64		#set to br-lan so that online can display IPv6 global address
	fi
	
	#set LAN IPv6 PPP Prefix
	if [ "$WAN_MODE" == "ppp" ]; then
		PPP_PREFIX=$(cat /tmp/PPP_PREFIXES 2>/dev/null)
		if [ $PPP_PREFIX ]; then
			ifconfig br-lan $PPP_PREFIX
		fi
	else
		rm /tmp/PPP_PREFIXES 2>/dev/null
	fi
fi

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