#!/bin/sh

### BEGIN INIT INFO
# Provides:             mqtt_node_client
# Required-Start:       $remote_fs $syslog $network
# Required-Stop:        $remote_fs $syslog $network
# Default-Start:
# Default-Stop:         0 1 6
# Short-Description:    MQTT v3.1 client and Modbus RTU/M-Bus master
# Description:
#  This combined implementation of the Python paho-mqtt client, pymodbus and
#  python-mbus provides the functionality to act as a gateway between Modbus RTU
#  resp. M-Bus devices and an OPC-server via MQTT. The values received from the
#  connected devices are logged in the CSV format and published on a MQTT broker
#  over WLAN afterwards.
### END INIT INFO

# When this option is enabled, the shell immediately exits if any command fails
set -e

PIDFILE=/var/run/mqtt_node_client.pid
DAEMON=/usr/local/sbin/mqtt_node_client.py

# Does the file exist and is the permission to execute it granted
test -x ${DAEMON} || exit 0

# Set all files to be created from here on to -rw-r--r--
umask 022

# Load init functions
. /lib/lsb/init-functions

# Start the daemon
start() {
  log_daemon_msg "Starting daemon:" "mqtt_server_client"
  if start-stop-daemon --start --quiet --oknodo --background --make-pidfile --pidfile ${PIDFILE} --startas /bin/bash -- -c "${DAEMON}"; then
      log_end_msg 0
  else
      log_end_msg 1
  fi
}

# Stop the daemon
stop() {
  log_daemon_msg "Stopping daemon:" "mqtt_server_client"
  if start-stop-daemon --stop --quiet --oknodo --pidfile ${PIDFILE}; then
      log_end_msg 0
      rm -f ${PIDFILE}
  else
      log_end_msg 1
  fi
}

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

  restart)
        stop
        start
        ;;

  status)
        status_of_proc -p ${PIDFILE} ${DAEMON} mqtt_server_client && exit 0 || exit $?
        ;;

  *)
        log_action_msg "Usage: /etc/init.d/mqtt_server_client {start|stop|restart|status}"
        exit 1
esac

exit 0