#! /bin/bash
#
# /etc/init.d/motion: Start the motion detection
#
### BEGIN INIT INFO
# Provides:	  motion
# Required-Start: $local_fs $syslog
# Required-Stop:
# Default-Start:  2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start Motion detection
# Description: loads motion and assigns privileges
### END INIT INFO

NAME=motion
PATH=/bin:/usr/bin:/sbin:/usr/sbin
DAEMON=/usr/bin/motion
PIDFILE=/var/run/$NAME.pid


trap "" 1
export LANG=C
export PATH

test -f $DAEMON || exit 0


case "$1" in
  start)
    echo "Starting motion detection : $NAME"
    start-stop-daemon --start --pidfile $PIDFILE --exec $DAEMON --chuid motion || true
    ;;

  stop)
    echo "Stopping motion detection : $NAME"
    start-stop-daemon --stop --pidfile $PIDFILE --oknodo --exec $DAEMON --retry 30 
    ;;

  status)
    echo "Status motion detection : $NAME"
    if (test -f $PIDFILE); then
        echo -n "Running process for $NAME : "
    	pidof $NAME  
    else
    	echo "Stopped"
    fi
    ;;  
    
  reload-config)
    echo "Reloading $NAME configuration"
    start-stop-daemon --stop --pidfile $PIDFILE --signal HUP --exec $DAEMON
    ;;

  restart-motion)
    echo "Restarting $NAME"
    start-stop-daemon --stop --pidfile $PIDFILE --oknodo --exec $DAEMON  --retry 30
    start-stop-daemon --start --pidfile $PIDFILE --exec $DAEMON --chuid motion
    ;;

  restart|force-reload)
    $0 restart-motion
    exit $?
    ;;

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

if [ $? == 0 ]; then
	echo .
	exit 0
else
	echo failed
	exit 1
fi
