#!/bin/sh

start() {
	# check lan device name(eth0 or br0) and auto-change it
	#lan_dev_name=$(uci -q -P /var/state get network.lan.device)
	#lan_dev_name=$(uci -q -P /var/state get network.lan.ifname)
	#wifi_exist=$(uci -q -P /var/state get network.wifi_device)
	#old_dev=$(grep ^if_prefix= /etc/tsp/tspc.conf | sed s/if_prefix=//g)
	#if [ "$wifi_exist" = "1" ]; then
 	#	lan_dev_name=br-lan
 	#else
 	#	lan_dev_name=eth0
	#fi
	# newest 2130 firmware would always use br-lan
	while [ 1 ]
	do
		tsp_enable=$(uci -q get tspc.@tspc[0].enable)
		if [ -f /etc/config/tspc ]; then
			wan_conn=$(uci -q -P /var/state get network.wan.up)
			if [ "$tsp_enable" = "1" ] && [ "$wan_conn" = "1" ]; then
				#echo "TSPC is enabled so try to initialize it..."
				proc_tspc=$(ps | grep [t]spc)
				if [ -z "$proc_tspc" ]; then
					echo "Try to start program : tspc...."
					tspc -vv -f /etc/tsp/tspc.conf
				else
					PID=$(ps|grep [t]spc|awk '{print $3}')
					#echo "tspc is now running.....PID=$PID"
				fi
			fi
		fi
		
		if [ "$tsp_enable" = "2" ]; then
			wan_conn=$(uci -q -P /var/state get network.wan.up)
			if [ "$wan_conn" = "1" ]; then
				#echo "DHCPv6(IA_PD) is enabled so try to initialize it..."
				proc_dhcp6c=$(ps | grep [w]ide-dhcp6c)
				if [ -z "$proc_dhcp6c" ]; then
					echo "Try to start program : wide-dhcp6c...."
					start_dhcp6c
				fi
			fi
		fi
		
		#if [ "$tsp_enable" = "3" ]; then
		#	proc_aiccu=$(ps | grep "[a]iccu")
		#	if [ -z "$proc_aiccu" ]; then
		#		echo "Try to start program : aiccu...."
		#		/etc/init.d/aiccu start
		#	fi
		#fi
		sleep 10
	done
}

stop() {
	proc_tspc=$(ps | grep [t]spc)
	if [ "$proc_tspc" != "" ]; then
		killall tspc
	fi
	
	proc_dhcp6c=$(ps | grep [w]ide-dhcp6c)
	if [ "$proc_dhcp6c" != "" ]; then
		killall wide-dhcp6c
		
		lan_inf=$(uci -q -P /var/state get network.lan.ifname)
		lan_ipv6=$(uci get ipv6.lan.global_addr)
		ifconfig $lan_inf $lan_ipv6/64 
	fi
	
	proc_aiccu=$(ps | grep "[a]iccu")
	if [ "$proc_aiccu" != "" ]; then
		killall aiccu
	fi
}

case "$1" in
	start) start;;
	stop) stop;;
esac
