#!/bin/sh

### BEGIN INIT INFO
# Provides:		check_3ware
# Required-Start:	$remote_fs $syslog
# Required-Stop:	$remote_fs $syslog
# Default-Start:	2 3 4 5
# Default-Stop:		1
# Short-Description:	Keep track of 3ware controller status
### END INIT INFO

set -e
#set -x

DAEMON="/opt/check_3ware/check_3ware.py"
NAME="check_3ware"
PATH="/sbin:/bin:/usr/sbin:/usr/bin"

test -x "${DAEMON}" || exit 0

case "${1}" in
	start)
		echo -n "Starting 3ware checker: "

		start-stop-daemon --start --background -m --oknodo --pidfile /var/run/check_3ware.pid --exec ${DAEMON}

		echo "${NAME}."
		;;

	stop)
		echo -n "Stopping 3ware checker: "

		start-stop-daemon --stop --pidfile /var/run/check_3ware.pid --oknodo --exec ${DAEMON}
		rm -f /var/run/check_3ware.pid

		echo "${NAME}."

		;;

	restart)
		echo -n "Stopping 3ware checker: "

		start-stop-daemon --stop --pidfile /var/run/check_3ware.pid --oknodo --exec ${DAEMON}
		rm -f /var/run/check_3ware.pid

		echo "${NAME}."
		Check_standalone_mode || exit 0
		echo -n "Starting 3ware checker: "

		start-stop-daemon --start --background -m --pidfile /var/run/check_3ware.pid --exec ${DAEMON}

		echo "${NAME}."
		;;

	status)
		PID="$(cat /var/run/check_3ware.pid 2>/dev/null)" || true

		if [ ! -f /var/run/check_3ware.pid ] || [ -z "${PID}" ]
		then
			echo "${NAME} is not running"
			exit 3
		fi

		if ps "${PID}" >/dev/null 2>&1
		then
			echo "${NAME} is running"
			exit 0
		else
			echo "${NAME} is not running"
			exit 1
		fi
		;;

	*)
		echo "Usage: /etc/init.d/${NAME} {start|stop|restart|status}"
		exit 1
		;;
esac

exit 0
