#!/bin/bash
#
### BEGIN INIT INFO
# Provides:        ebusd
# Required-Start:  $network $remote_fs $syslog
# Required-Stop:   $network $remote_fs $syslog
# Default-Start:   2 3 4 5
# Default-Stop:    0 1 6
# Short-Description: controls ebusd, the daemon for communication with eBUS heating systems.
### END INIT INFO

DAEMON=/usr/bin/ebusd
PIDFILE_PREFIX=/var/run/ebusd
PIDFILE_SUFFIX=.pid

if test -f /lib/lsb/init-functions; then
	. /lib/lsb/init-functions
else
	. /etc/init.d/functions

	log_daemon_msg()  { logger "$@"; }
	log_end_msg()     { [ $1 -eq 0 ] && RES=OK; logger ${RES:=FAIL}; }
	log_failure_msg() { logger "FAIL $@"; }
	log_warning_msg() { logger "WARN $@"; }
	status_of_proc () { status $3; }

fi

[ -r /etc/default/ebusd ] && . /etc/default/ebusd

if [ ! -x $DAEMON ]; then
	log_failure_msg "$DAEMON is not available or not executable."
	exit 5
fi

ALL_OPTS=${!EBUSD_OPTS*}
if [ ${#ALL_OPTS[@]} -lt 1 ]; then
  ALL_OPTS[0]=EBUSD_OPTS
fi
instance="EBUSD_OPTS$2"
instance=${!instance}

start_instance () {
	local opts suffix
	opts=$1
	shift
	suffix="${opts#EBUSD_OPTS}"
	log_daemon_msg "Starting ebusd${suffix}" ebusd
	pidfile=$PIDFILE_PREFIX${suffix}$PIDFILE_SUFFIX
	start-stop-daemon --start --quiet --oknodo --pidfile $pidfile --exec $DAEMON -- --pidfile $pidfile ${!opts}
	log_end_msg $?
}

stop_instance () {
	local opts suffix
	opts=$1
	shift
	suffix="${opts#EBUSD_OPTS}"
	log_daemon_msg "Stopping ebusd${suffix}" ebusd
	pidfile=$PIDFILE_PREFIX${suffix}$PIDFILE_SUFFIX
	start-stop-daemon --stop --quiet --oknodo --pidfile $pidfile
	log_end_msg $?
	rm -f $PIDFILE_PREFIX${suffix}$PIDFILE_SUFFIX
}

case $1 in
	start)
		if [ -z "$2" ]; then
			for opts in $ALL_OPTS; do
				start_instance $opts
			done
		elif [ -z "$instance" ]; then
			log_failure_msg "ebusd$2 is not configured"
		else
			start_instance EBUSD_OPTS$2
		fi
  		;;
	stop)
		if [ -z "$2" ]; then
			for opts in $ALL_OPTS; do
				stop_instance $opts
			done
		else
			if [ -z "$instance" ]; then
				log_warning_msg "ebusd$2 is not configured"
			fi
			stop_instance EBUSD_OPTS$2
		fi
  		;;
	restart|force-reload)
		ARGS=($@)
		$0 stop ${ARGS[@]:1} && sleep 2 && $0 start ${ARGS[@]:1}
  		;;
	status)
		if [ -z "$2" ]; then
			for opts in $ALL_OPTS; do
				suffix=${opts#EBUSD_OPTS}
				pidfile=$PIDFILE_PREFIX$suffix$PIDFILE_SUFFIX
				status_of_proc -p $pidfile $DAEMON ebusd$suffix
			done
		else
			if [ -z "$instance" ]; then
				log_warning_msg "ebusd$2 is not configured"
			fi
			pidfile=$PIDFILE_PREFIX$2$PIDFILE_SUFFIX
			status_of_proc -p $pidfile $DAEMON ebusd$2
		fi
		;;
	*)
		echo "Usage: $0 {start|stop|restart|force-reload|status} [instance]"
		exit 2
		;;
esac
