#! /bin/sh -e
#
# /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

# Ported to new debian way using sh and /lib/lsb/init-functions
# by Angel Carpintero <ack@telefonica.net>

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

ENV="env -i LANG=C PATH=/usr/local/bin:/usr/bin:/bin"

. /lib/lsb/init-functions

test -x $DAEMON || exit 0

running() {
    if [ -f ${PIDFILE} ]; then
        pidof $NAME
    fi
}


case "$1" in
  start)
    log_daemon_msg "Starting motion detection : $NAME"
    RUNNING=$(running)
    if [ -n "$RUNNING" ]; then
       log_failure_msg "Already runnning"
    else
        if start-stop-daemon --start --exec ${DAEMON} --chuid motion; then
            log_end_msg 0
        else
            log_end_msg 1
        fi
    fi 
    ;;

  stop)
    RUNNING=$(running)
    log_daemon_msg "Stopping motion detection : $NAME"
    if [ -n "$RUNNING" ]; then
        if start-stop-daemon --stop --oknodo --exec ${DAEMON} --retry 30 ; then
            log_end_msg 0
        else
            log_end_msg 1
        fi
    else
        log_failure_msg "Not runnning"
    fi
    ;;

  status)
    RUNNING=$(running)
    if [ -n "$RUNNING" ]; then
        log_success_msg "$NAME is running"
        exit 0
    else
        log_success_msg "$NAME is not running"
        exit 3
    fi

    ;;  
    
  reload-config)
    log_action_begin_msg "Reloading $NAME configuration"
    if start-stop-daemon --stop --signal HUP --exec $DAEMON; then
        log_action_end_msg 0
    else
        log_action_end_msg 1
    fi
    ;;

  restart-motion)
    log_daemon_msg "Restarting $NAME"
    $0 stop
    $0 start
    ;;

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

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

exit 0
