#!/bin/bash

## Fill in name of program here.
PROG="fixpermissions-inotify"
PROG_PATH="/usr/local/bin" ## Not need, but sometimes helpful (if $PROG resides in /opt for example).
DAEMON="$PROG_PATH/$PROG"
DAEMON_ARGS=""
PID_PATH="/var/run/"
PID_FILE="$PID_PATH/$PROG.pid"

start() {
    # Return 
    # 0 if daemon has been started
    # 1 if daemon was already running
    # 2 if daemon could not be started

    echo -n "Starting $PROG: "
    
    start-stop-daemon --start --quiet --pidfile $PID_FILE --startas $DAEMON -m --test > /dev/null
    if [ $? != 0 ]; then
        echo "Already running"
        return 1
    fi

    start-stop-daemon --start --quiet --make-pidfile --pidfile $PID_FILE --background --startas $DAEMON -- $DAEMON_ARGS
    if [ $? != 0 ]; then
        echo "ERROR"
        return 2
    fi

    echo "OK"
    return 0
}

stop() {
    echo -n "Stopping $PROG: "

    start-stop-daemon --stop --quiet --pidfile $PID_FILE --test > /dev/null
    if [ $? != 0 ]; then
        echo "Already stopped"
        return 1
    fi

    start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PID_FILE
    if [ $? != 0 ]; then
        echo "ERROR"
        return 2
    fi

    # Many daemons don't delete their pidfiles when they exit.
    rm -f $PID_FILE

    echo "OK"
    return 0
}

status() {

    start-stop-daemon --status --quiet --pidfile $PID_FILE
    RETVAL=$?
    case $RETVAL in
        0)
            echo "$PROG is running"
            ;;
        1)
            echo "$PROG is not running and the pid file exists"
            ;;
        3)
            echo "$PROG is not running"
            ;;
        *)
            echo "unable to determine status"
            ;;
    esac

    return $RETVAL
}

## Check to see if we are running as root first.
## Found at http://www.cyberciti.biz/tips/shell-root-user-check-script.html
if [ "$(id -u)" != "0" ]; then
    echo "This script must be run as root" 1>&2
    exit 1
fi

case "$1" in
    start)
        start
        exit $?
    ;;
    stop)
        stop
        exit $?
    ;;
    status)
        status
        exit $?
    ;;
    reload|restart|force-reload)
        stop
        start
        exit $?
    ;;
    **)
        echo "Usage: $0 {start|stop|status|reload}" 1>&2
        exit 1
    ;;
esac