#!/bin/sh /etc/rc.common
START=99

boot() {
	stop
#	if [ `uci get iec101_104.@iec101_104[0].iec101_104_enable` == 1 ]; then
	start
#	fi
}

start() {
	test_valid_values 2>/dev/null
	if [[ "`uci get serial1.Line.mode 2>/dev/null`" == "iec101" || "`uci get serial.Line.mode 2>/dev/null`" == "iec101" ]]
	then
		if [ "`uci get iec101_104.101_104.enable 2>/dev/null`" == 1 ]; then
			/usr/sbin/iec101_104.sh &
			/usr/sbin/iec101_104_wd.sh &
		fi
	fi	

}

stop() {
	kill -9 `pidof 101_104` 2>/dev/null
	ps | grep -w "iec101_104_wd.sh" | grep -v grep | awk '{print $1}' | xargs kill -16 2>/dev/null
	rm -rf /tmp/iec104_stats.txt 2>/dev/null
	return 0
}
reload() {
	stop
#	if [ `uci get iec101_104.@iec101_104[0].iec101_104_enable` == 1 ]; then
	if [[ "`uci get iec101_104.101_104.enable 2>/dev/null`" == 1 ]] &&
	   [[ "`uci get serial1.Line.mode 2>/dev/null`" != "iec101" ]] &&
	   [[ "`uci get serial.Line.mode 2>/dev/null`" != "iec101" ]]
	then
		echo "WARNING: Serial 1 or Serial 2 Mode is not IEC 101 to 104" >> /tmp/luci_message_101
	fi
	start
#	fi	
}
test_valid_values() {
	if [[ "`uci get iec101_104.101.asduaddr_101`" == "" ]]; then
	    uci set iec101_104.101.asduaddr_101=1
	fi
	if [[ "`uci get iec101_104.101.linkaddr`" == "" ]]; then
	    uci set iec101_104.101.linkaddr=1
	fi
	if [[ "`uci get iec101_104.104.asduaddr_104`" == "" ]]; then
	    uci set iec101_104.104.asduaddr_104=1
	fi
	if [[ "`uci get iec101_104.104.t1`" == "" ]]; then
	    uci set iec101_104.104.t1=15000
	fi
	if [[ "`uci get iec101_104.104.t2`" == "" ]]; then
	    uci set iec101_104.104.t2=10000
	fi
	if [[ "`uci get iec101_104.104.t3`" == "" ]]; then
	    uci set iec101_104.104.t3=20000
	fi
	if [[ "`uci get iec101_104.104.port`" == "" ]]; then
	    uci set iec101_104.104.port=2404
	fi
	uci commit
}
