#! /bin/sh

### BEGIN INIT INFO
# Provides:         eprodbus
# Required-Start:   $remote_fs $syslog
# Required-Stop:    $remote_fs $syslog
# Default-Start:    2 3 4 5
# Default-Stop:     0 1 6
# Short-Description:    eprodbus
# Description:
#   Log van stats
### END INIT INFO

set -e

PIDFILE=/var/run/eprodbus.pid
PYTHON=/usr/bin/python
DAEMON=/home/root/vanlogger/epro/eprodbus.py

test -x ${DAEMON} || exit 0

umask 022

. /etc/init.d/functions

export PATH="${PATH:+$PATH:}/usr/sbin:/sbin"

case "$1" in
    start)
        echo "Starting eprodbus"
        if start-stop-daemon --start --quiet --oknodo --background --make-pidfile --pidfile ${PIDFILE} --exec ${PYTHON} -- ${DAEMON} ; then
            exit 0
        else
            exit 1
        fi
        ;;
    stop)
        echo "Stopping eprodbus"
        if start-stop-daemon --stop --quiet --oknodo --pidfile ${PIDFILE}; then
            rm -f ${PIDFILE}
            exit 0
        else
            exit 1
        fi
        ;;

    restart)
        echo "Restarting eprodbus"
        if start-stop-daemon --stop --quiet --oknodo --retry 30 --pidfile ${PIDFILE}; then
            rm -f ${PIDFILE}
        fi
        if start-stop-daemon --start --quiet --oknodo --background --make-pidfile --pidfile ${PIDFILE} --exec ${PYTHON} -- ${DAEMON} ; then
            exit 0
        else
            exit 1
        fi
        ;;

    status)
	if [ ! -e ${PIDFILE} ]; then
	  running=0
	else
	    pid=$(cat ${PIDFILE})
	    ps -w | grep -v grep | grep -q "$pid"
	    running=$((!$?))
	fi
	if [ $running -ne 0 ]; then
	  echo "eprodbus (pid $pid) is running..."
	  exit 0
	else
	    echo "eprodbus is stopped"
	    exit 1
	fi
        ;;

    *)
        echo "Usage: $0 {start|stop|restart|status}"
        exit 1
esac

exit 0
