#!/bin/sh
### BEGIN INIT INFO
# Provides:          brickd
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: brickd
# Description:       Brick Daemon
### END INIT INFO

# brickd (Brick Daemon)
# Copyright (C) 2011-2012 Olaf Lüke <olaf@tinkerforge.com>
# Copyright (C) 2013 Matthias Bolte <matthias@tinkerforge.com>
#
# based on skeleton from Debian GNU/Linux
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public
# License along with this program; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/bin/brickd
OPTIONS=--daemon
NAME=brickd
PIDFILE=/var/run/$NAME.pid
DESC="Brick Daemon"

test -f $DAEMON || exit 0

set -e

case "$1" in
  start)
	echo -n "Starting $DESC: "
	start-stop-daemon --verbose --pidfile $PIDFILE --exec $DAEMON --start -- $OPTIONS
	;;
  stop)
	echo -n "Stopping $DESC: "
	start-stop-daemon --verbose --pidfile $PIDFILE --stop
	;;
  restart|force-reload)
	echo "Restarting $DESC: "
	start-stop-daemon --verbose --pidfile $PIDFILE --stop
	sleep 1
	start-stop-daemon --verbose --pidfile $PIDFILE --exec $DAEMON --start -- $OPTIONS
	;;
  status)
	echo -n "Status of $DESC: "
	if [ -n "${PIDFILE:-}" -a -r "$PIDFILE" ]; then
		PID=`cat "$PIDFILE"`
		if [ -n "${PID:-}" ]; then
			if $(kill -0 "${PID:-}" 2> /dev/null); then
				echo "running (pid $PID)"
			elif ps "${PID:-}" > /dev/null 2>&1; then
				echo "running (pid $PID)"
			else
				echo "stopped"
			fi
		else
			echo "stopped"
		fi
	else
		echo "stopped"
	fi
	;;
  *)
	N=/etc/init.d/$NAME
	echo "Usage: $N {start|stop|restart|force-reload|status}" >&2
	exit 1
	;;
esac

exit 0
