# -*-Shell-script-*-
#
# eyesdn     This file contains functions to be used by all other
#                     eyesdn shell scripts in the /etc/init.d directory.
#

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

test -x "${DAEMON}" || exit 0

pidfile=${PIDFILE-/var/run/${SRV_NAME}.pid}
lockfile=${LOCKFILE-/var/lock/subsys/${SRV_NAME}}

STOP_TIMEOUT=${STOP_TIMEOUT-10}
USER=root

do_start()
{
    local pid
    
    mkdir -p $(dirname ${lockfile})
    mkdir -p $(dirname ${pidfile})
    
    echo -n $"Starting ${SRV_NAME}: "
    runuser -l "${USER}" -c "${DAEMON} >&/dev/null &" >&/dev/null && echo_success || echo_failure
    RETVAL=$?
    echo
    [ ${RETVAL} -eq 0 ] && touch ${lockfile}
    pid=`ps -aefw | grep "${DAEMON}" | grep -v " grep " | awk '{print $2}'`
    if [ -n "${pid}" ] ;then
        echo ${pid} >${pidfile}
    fi
}

start()
{
    if [ ! -f "${lockfile}" ] ; then
        do_start
    else
        echo "${SRV_NAME} is locked. checking if it is running"
        if status -p ${pidfile} "${DAEMON}" ;then
            echo "already running with PID:$(cat ${pidfile})"
            RETVAL=1
        else
            echo "not running, removing lock file"
            rm -f ${lockfile}
            do_start
        fi
    fi
    return ${RETVAL}
}

stop()
{
    echo -n $"Stopping ${SRV_NAME}: "
    killproc -p ${pidfile} -d ${STOP_TIMEOUT} "${DAEMON}" >&/dev/null && echo_success || echo_failure
    RETVAL=$?
    echo
    [ $RETVAL = 0 ] && rm -f ${lockfile} ${pidfile}
}

# See how we were called.
case "$1" in
    start)
	start
	;;
    stop)
	stop
	;;
    status)
        status -p ${pidfile} "${DAEMON}"
	RETVAL=$?
	;;
    restart)
	stop
	start
	;;
    condrestart|try-restart)
	if status -p ${pidfile} "${DAEMON}" >&/dev/null; then
	    stop
	    start
	fi
	;;
    *)
	echo $"Usage: ${SRV_NAME} {start|stop|restart|condrestart|try-restart|status|help}"
	RETVAL=2
esac
