#! /bin/sh
#
# Startup script for HomEvenT.
# 
# Based on a skeleton written by Miquel van Smoorenburg <miquels@cistron.nl>
# and modified for Debian by Ian Murdock <imurdock@gnu.ai.mit.edu>.
#
# Version:	@(#)skeleton  1.9  26-Feb-2001  miquels@cistron.nl
#

PATH=/usr/lib/homevent:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/homevent
NAME=homevent
DESC=homevent

DAEMON_OPTS=""
DAEMON_CFG="/etc/homevent/daemon.he"
LOGLEVEL=user.info
ERRLEVEL=user.warn
export PYTHONPATH=/etc/homevent

test -x $DAEMON || exit 0

# Include homevent defaults if available
if [ -f /etc/default/homevent ] ; then
	. /etc/default/homevent
fi
test -f "$DAEMON_CFG" || exit 0

mkdir -p /var/run/homevent /var/cache/homevent
chmod 755 /var/run/homevent /var/cache/homevent
chown -R homevent /var/run/homevent /var/cache/homevent

set -e

case "$1" in
  start)
	echo -n "Starting $DESC: "
	cd /var/lib/homevent
	( sudo -u homevent env PATH=/usr/lib/homevent:/bin:/usr/bin $DAEMON --pidfile=/var/run/homevent/pid $DAEMON_OPTS $DAEMON_CFG </dev/null | logger -p $LOGLEVEL -t homevent ) 2>&1 | logger -p $ERRLEVEL -t homevent &
	echo "$NAME."
	;;
  debug)
	shift
	cd /var/lib/homevent
	exec sudo -u homevent $DAEMON $DAEMON_OPTS $@ $DAEMON_CFG
	;;
  stop)
	echo -n "Stopping $DESC: "
	pid=$(cat /var/run/homevent/pid 2>/dev/null)
	test -n "$pid" && kill -0 $pid 2>/dev/null || exit 0
	start-stop-daemon --stop --quiet --pidfile /var/run/homevent/pid
	for f in . . . . . . . . . . ; do
		if ! kill -0 $pid 2>/dev/null; then break; fi
		echo -n $f
		sleep 1
	done
	if kill -0 $pid 2>/dev/null; then echo " -- still running?"; exit 1; fi
	echo " $NAME."
	;;
  reload)
	echo "Reloading $DESC configuration files."
	start-stop-daemon --stop --signal 1 --quiet --pidfile /var/run/homevent/pid
	;;
  force-reload)
	# check whether $DAEMON is running. If so, restart
	start-stop-daemon --stop --test --quiet --pidfile /var/run/homevent/pid \
	&& $0 restart \
	|| exit 0
	;;
  restart)
    echo "Restarting $DESC: "
	$0 stop
	$0 start
	;;
  *)
	N=/etc/init.d/$NAME
	echo "Usage: $N {start|stop|restart|reload|force-reload|debug}" >&2
	exit 1
	;;
esac

exit 0
