# -*-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}}

OMG_EYESDN_DISABLED_FILE=/data/eyesdnDisabled
OMG_CONFIG_FILE=/data/config.lua

STOP_TIMEOUT=${STOP_TIMEOUT-10}
USER=root

check_if_disabled()
{
    local RETVAL=1

    test -e "${OMG_EYESDN_DISABLED_FILE}" && RETVAL=0
    if test -r "${OMG_CONFIG_FILE}"; then
        grep -qi "bool  *EyesdnEnabled *= *false" "${OMG_CONFIG_FILE}" && RETVAL=0
    fi
    return ${RETVAL}
}

do_start()
{
    local pid

    mkdir -p $(dirname ${lockfile})
    mkdir -p $(dirname ${pidfile})

    ulimit -c 1000000

    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()
{
    local RETVAL=0

    if check_if_disabled; then
        echo "${SRV_NAME} is disabled"
        RETVAL=1
    elif [ ! -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
