#!/bin/sh
#
# Motion	This shell script takes care of starting and stopping
# 		motion service.
#
# chkconfig:	345 85 15
# description:	Motion Detection System.  It is used to detect \
#		movement based on compare images.

# Source function library.
. /etc/rc.d/init.d/functions

# Initial values:
motion=${MOTION-/usr/bin/motion}
STARTUP_OPTIONS=""
PIDFILE=/var/run/motion/motion.pid

# Get service config
[ -f /etc/sysconfig/motion ] && . /etc/sysconfig/motion

start() {
	if [ ! -f /var/lock/subsys/motion ]; then
		msg_starting motion
		daemon --user motion ${motion} ${STARTUP_OPTIONS}
		RETVAL=$?
		if [ $RETVAL -eq 0 ] ; then
			echo `ps axf | awk -vprog="$motion" '!/awk/ && $0 ~ prog {print $1; exit}'` > ${PIDFILE}
			touch /var/lock/subsys/motion
		fi
	else
		msg_already_running motion
	fi
}

stop() {
	if [ -f /var/lock/subsys/motion ]; then
		msg_stopping motion
		killproc --pidfile ${PIDFILE} motion
		RETVAL=$?
		rm -f /var/lock/subsys/motion ${PIDFILE}
	else
		msg_not_running motion
	fi
}

RETVAL=0
# See how we were called.
case "$1" in
start)
	start
	;;
stop)
	stop
	;;
status)
	status motion
	RETVAL=$?
	;;
restart|force-reload)
	stop
	start
	;;
reload)
	if [ -f /var/lock/subsys/motion ]; then
		msg_reloading motion
		killproc --pidfile ${PIDFILE} motion -HUP
		RETVAL=$?
	else
		msg_not_running motion
		exit 7
	fi
	;;
*)
	msg_usage "$0 {start|stop|restart|force-reload|reload|status}"
	exit 3
esac

exit $RETVAL
