#!/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
  
	sed -e s/^if_prefix=$old_dev/if_prefix=$lan_dev_name/g /etc/tsp/tspc.conf > /tmp/tspc.conf
	mv /tmp/tspc.conf /etc/tsp/tspc.conf

	while [ 1 ]
	do
		if [ -f /etc/config/tspc ]; then
			tsp_enable=$(uci -q get tspc.@tspc[0].enable)
			wan_conn=$(uci -q -P /var/state get network.wan.up)
			if [ $tsp_enable -eq 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
		sleep 10
	done
}

stop() {
	killall tspc
}

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