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

boot() {
	stop
	if  [[ ! `ls /etc/iec104_mqtt.csv  2>/dev/null` ]] || [[ "`ls -l /etc/iec104_mqtt.csv  | awk '{print$5}'  2>/dev/null`" == 0 ]]; then exit ; fi;
	if [ `uci get iec104_applications.mqtt.enable  2>/dev/null` == 1 ]; then
		/usr/bin/iec104_mqtt reload &> /dev/null &
	fi
}

start() {
	if  [[ ! `ls /etc/iec104_mqtt.csv  2>/dev/null` ]] || [[ "`ls -l /etc/iec104_mqtt.csv  | awk '{print$5}'  2>/dev/null`" == 0 ]]; then exit ; fi;
	if [ `uci get iec104_applications.mqtt.enable  2>/dev/null` == 1 ]; then
		/usr/bin/iec104_mqtt &> /dev/null &
	fi
}

stop() {
	killall iec104_mqtt &> /dev/null
    killall mosquitto_sub &> /dev/null
	return 0
}
restart() {
	stop
    file_name=`uci get iec104_applications.mqtt.config_file 2>/dev/null`
    state=`uci get iec104_applications.mqtt.enable 2>/dev/null`
    if [[ ! -f "$file_name" ]] && [[ $state == 1 ]]
    then
        echo "ERROR: Configuration file not present"
        echo "ERROR: Configuration file not present" >> /tmp/luci_message_104_mqtt
        exit
    elif [[ ! -s "$file_name" ]] && [[ $state == 1 ]]
    then
        echo "ERROR: Empty configuration file"
        echo "ERROR: Empty configuration file" >> /tmp/luci_message_104_mqtt
        exit
    fi
    if [ $state == 1 ]; then
        rm -rf /etc/iec104_mqtt.csv 2>/dev/null
	    cp "`uci get iec104_applications.mqtt.config_file`" /etc/iec104_mqtt.csv
        start
    fi
}
