#!/bin/sh /etc/rc.common

START=96
SERVICE_DAEMONIZE=1
INTERVAL=35    # Refresh interval is 30s for Web

is_adopted()
{
	local is_adopted="1"
	local cdId=$(cat /etc/config/controller.conf | sed 's/,/\n/g' | grep "csId" | sed 's/:/\n/g' | sed '1d' | sed 's/"//g' | sed 's/^[ \t]*//g')
	local ctrlModeFlag=$(cat /etc/config/controller.conf | sed 's/,/\n/g' | grep "ctrlModeFlag" | sed 's/:/\n/g' | sed '1d' | sed 's/"//g' | sed 's/^[ \t]*//g')
	if [ "$cdId" == "c21f969b5f03d33d43e04f8f136e7682" -o "$ctrlModeFlag" == "0" ]; then
		is_adopted="0"
	fi
	echo "$is_adopted"
}

start()
{
	status_ipstat=$(uci get ipstat.setting.status)
	status_ifstat=$(uci get ifstat-mini.setting.status)
	dynamic_statistical_switch=$(uci -c /etc/profile.d get profile.@global[0].sfe_ipstat_dynamic_support)
	if [ -z "$status_ipstat" -o -z "$status_ifstat" ]; then
	        return 0
	fi
	if [ "$status_ifstat" == "on" -a "$status_ipstat" == "on" ];then
		pid=`pgrep hwnat_ipstat`
		[ ! -z "$pid" ] && echo "hwnat_ipstat is already running." >/dev/console && return
		#setting hwnat entry timeout to 15 secs
		echo 2 ${INTERVAL} > /sys/kernel/debug/hnat/hnat_setting 2>/dev/null
		echo 3 ${INTERVAL} > /sys/kernel/debug/hnat/hnat_setting 2>/dev/null
		echo 4 ${INTERVAL} > /sys/kernel/debug/hnat/hnat_setting 2>/dev/null
		if [ -n "$dynamic_statistical_switch" -a "$dynamic_statistical_switch" == "1" ];then
			echo 1 > /proc/net/sfe_ipstat_switch
		fi
		##for 605w hwnat
		local is_adopted=$(is_adopted)
		local hnat_sens=`uci -c /etc/profile.d  get profile.@hwnat[0].traffic_stat`
		[ "$hnat_sens" == "1" ] && [ "$is_adopted" == "0" ] && {
			uci set hwnat.module.traffic_stat=1
			uci commit hwnat
			/lib/cfg_save/config.sh save
			echo "!!!!hwnat traffic_stat set to 1" > /dev/console
			. /bin/hwnat -y
		}
		service_start /usr/sbin/hwnat_ipstat
	fi
}

stop()
{
	service_stop /usr/sbin/hwnat_ipstat
	##for 605w hwnat
	local hnat_sens=`uci -c /etc/profile.d  get profile.@hwnat[0].traffic_stat`
	[ "$hnat_sens" == "1" ] && {
		uci set hwnat.module.traffic_stat=0
		uci commit hwnat
		/lib/cfg_save/config.sh save
		echo "!!!!hwnat traffic_stat set to 0" > /dev/console
		. /bin/hwnat -y
	}
	/usr/sbin/usp_cmd_conn traffic_stats_module clean_ifstat
	/usr/sbin/usp_cmd_conn traffic_stats_module clean_ipstat
	dynamic_statistical_switch=$(uci -c /etc/profile.d get profile.@global[0].sfe_ipstat_dynamic_support)
	if [ -n "$dynamic_statistical_switch" -a "$dynamic_statistical_switch" == "1" ];then
		echo 0 > /proc/net/sfe_ipstat_switch
	fi
}

restart()
{
        stop
        start
}

reload()
{
        restart
}


