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

boot() {
	stop
	test_valid_values
	start
}

start() {

	if [[ "`uci get serial1.Line.mode 2>/dev/null`" == "dnp3" || "`uci get serial.Line.mode 2>/dev/null`" == "dnp3" ]]
	then
		if  [[ ! `ls /etc/MODBUS_DNP3_Configuration_MH.csv` ]] || [[ "`ls -l /etc/MODBUS_DNP3_Configuration_MH.csv  | awk '{print$5}'`" == 0 ]]; then exit ; fi;
		if [ `uci get dnp3.main.dnp3_enable` == 1 ]; then
			/usr/bin/dnp3outstation &> /dev/null &
			if [[ "`uci get serial1.Line.mode 2>/dev/null`" == "dnp3" ]]
			then
				/usr/bin/modbusmaster-lite "/dev/ttyS6" &> /dev/null &
			else
				/usr/bin/modbusmaster-lite "/dev/ttyS3" &> /dev/null &
			fi
		fi
	fi
}

restart() {

	stop
	test_valid_values 2>/dev/null

	file_name=`uci get dnp3.modbus.config_file 2>/dev/null`
	state=`uci get dnp3.main.dnp3_enable 2>/dev/null`
	# Using modbus command to validate the config file
	if [[ ! -f "$file_name" ]] && [[ $state == 1 ]]
	then
		echo "ERROR: Configuration file not present"
		echo "ERROR: Configuration file not present" >> /tmp/luci_message_dnp
	elif [[ ! -s "$file_name" ]] && [[ $state == 1 ]]
	then
		echo "ERROR: Empty configuration file"
		echo "ERROR: Empty configuration file" >> /tmp/luci_message_dnp
	fi
	if [[ -f /usr/bin/modbusmaster ]] && [[ -s "$file_name" ]]
	then
		modbusmaster -T "`uci get dnp3.modbus.config_file`" > /dev/null 2>&1
		if [[ $? == 1 ]]
		then
			echo "ERROR: Invalid configuration file"
			echo "ERROR: Invalid configuration file" >> /tmp/luci_message_dnp
		fi
	fi
	if [[ $state == 1 ]] && [[ "`uci get serial1.Line.mode 2>/dev/null`" != "dnp3" ]] && [[ "`uci get serial.Line.mode 2>/dev/null`" != "dnp3" ]]
	then
		echo "WARNING: Serial 1 or Serial 2 Mode is not DNP3" >> /tmp/luci_message_dnp
	fi

	if [ "`uci get dnp3.main.dnp3_enable 2>/dev/null`" == 1 ]; then
		rm -rf /etc/MODBUS_DNP3_Configuration_MH.csv 2>/dev/null
		cp "`uci get dnp3.modbus.config_file`" /etc/MODBUS_DNP3_Configuration_MH.csv
		start
	else
	   ##delete previous config file
           rm /etc/MODBUS_DNP3_Configuration_MH.csv
	fi

}

stop() {
        killall -9 dnp3outstation 2>/dev/null
	killall -9 modbusmaster-lite 2>/dev/null
	rm -rf /tmp/dnp3_stats.txt 2>/dev/null
	return 0
}

reload() {
	stop
	start
}

test_valid_values() {
	if [[ "`uci get dnp3.outstation.port`" == "" ]]; then
	    uci set dnp3.outstation.port=2000
	fi
	if [[ "`uci get dnp3.outstation.lport`" == "" ]]; then
	    uci set dnp3.outstation.lport=10
	fi
	if [[ "`uci get dnp3.outstation.rport`" == "" ]]; then
	    uci set dnp3.outstation.rport=100
	fi
	if [[ "`uci get dnp3.outstation.poll`" == "" ]]; then
	    uci set dnp3.outstation.poll=10
	fi
	uci commit
}
