#!/bin/sh

### BEGIN INIT INFO
# Provides:     ueyeusbdrc
# Required-Start:   $local_fs
# Required-Stop:    $local_fs
# Default-Start:    2 3 4 5
# Default-Stop:     0 1 6
# Short-Description:    Control the USB uEye Linux daemon
### END INIT INFO

# chkconfig: 2345 20 80
# description: Control the USB uEye Linux daemon

# Return codes
# 0: Success
# 1: Error creating daemon run directory
# 2: Daemon is already running
# 3:
# 4: Daemon did not terminate
# 5: No pidfile found

N=/etc/init.d/ueyeusbdrc

# RC settings
# daemon run directory - this is where the daemon will create its PID file and sockets
RUNDIR="/var/run/ueyed"
# PID file name
PIDFILE="ueyeusbd.pid"
# where to find ueyed
DAEMON_BINDIR="/opt/ids/ueye/bin"
# daemon name
DAEMON="ueyeusbd"
# daemon user name
DAEMON_USER="ueyed"
# daemon groupsudo gedit /usr
DAEMON_GROUP="ueye"
# daemon configuration file
DAEMON_CONF="/etc/ids/ueye/ueyeusbd.conf"
# daemon terminate wait time
TERMINATEWAIT=3
# daemon priority (highest: -20, lowest: 19)
NICEVALUE=-10

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:"${DAEMON_BINDIR}"
DAEMONSTATUS=-1

# Check daemon status
checkdaemonstatus()
{
    if [ -e "${RUNDIR}/${PIDFILE}" ]
    then
        PID=$(cat ${RUNDIR}/${PIDFILE})
        if [ -d /proc/${PID} ]
        then
            PROCESSNAME=$(ps -p ${PID} -o comm=)
            if [ "${PROCESSNAME}" = "${DAEMON}" ]
            then
                DAEMONSTATUS=0
            else
                # another process is running with the pid stored in the pidfile
                #  => returning DAEMONSTATUS=1 forces cleanup.
                DAEMONSTATUS=1
            fi
        else
            DAEMONSTATUS=1
        fi
    else
        DAEMONSTATUS=2
    fi
}

# Check daemon status
printdaemonstatus()
{
    checkdaemonstatus
    case "${DAEMONSTATUS}" in
        0)
            echo "${DAEMON} is running.";
        ;;
        1)
            echo "${DAEMON} is not running but pidfile exists."
        ;;
        2)
            echo "${DAEMON} is not running."
        ;;
        *)
        ;;
    esac
}

# clean up orphaned files
cleanup()
{
    rm -f ${RUNDIR}/*usb*
}

# Print an error message and exit
# Usage: errmsg message return-code
errmsg()
{
    echo ${1} >&2
    exit ${2}
}

# Runlevel control
case "${1}" in
  start)
      # daemon startup - clean orphaned sockets that may persist after
      # unclean daemon shutdown
    echo -n "Starting ${DAEMON}... "
    # create run directory (some distributions may have it on a ramdisk)
    if [ ! -d "${RUNDIR}" ]
    then
        mkdir -p "${RUNDIR}" > /dev/null 2>&1 || errmsg "Runtime directory doesn't exist and cannot be created." 1
        chown ${DAEMON_USER}:${DAEMON_GROUP} "${RUNDIR}"
    fi
    # Refuse to start if a PID file exists
    checkdaemonstatus
    case "${DAEMONSTATUS}" in
        0) # the daemon is already running
        errmsg "${DAEMON} is already running." 2
        ;;
        1) # daemon is not running, but there is a PID file
        cleanup
        ;;
        2) # daemon is not running
        cleanup
        ;;
    esac
    # start the daemon
    "${DAEMON_BINDIR}/${DAEMON}" -c "${DAEMON_CONF}" -P "${RUNDIR}/${PIDFILE}"
    sleep 1
    printdaemonstatus
    if [ $DAEMONSTATUS -eq 0 ] && [ $NICEVALUE -ne 0 ]; then
        PID=$(cat ${RUNDIR}/${PIDFILE})
        renice -n $NICEVALUE -g $PID > /dev/null 2>&1 || errmsg "Unable to set daemon priority." 1
    fi
    ;;
  stop)
    echo -n "Stopping ueyed... "
    checkdaemonstatus
    case "${DAEMONSTATUS}" in
        0)
        # the daemon is running
        kill -TERM $(cat ${RUNDIR}/${PIDFILE})
        echo -n "Waiting ${TERMINATEWAIT}s for ${DAEMON} to terminate... "
        sleep ${TERMINATEWAIT}
        checkdaemonstatus
        if [ ${DAEMONSTATUS} -eq 0 ]
        then
            errmsg "${DAEMON} is still running. Check the system log for more information. One may force termination by calling \"${0} force-stop\"." 4
        fi
        ;;
        1)
        # daemon is not running, but there is a PID file
        cleanup
        ;;
        2)
        # daemon is not running
        errmsg "No pidfile found. Cannot stop ${DAEMON}" 5
        ;;
    esac
    echo "Stopped ${DAEMON}."
    ;;
  force-stop)
    echo -n "Killing ${DAEMON}... "
    if [ -e ${RUNDIR}/${PIDFILE} ]
    then
        PID=$(cat ${RUNDIR}/${PIDFILE})
        cleanup
        kill -KILL ${PID} > /dev/null 2>&1
        echo "Done."
    else
        cleanup
        errmsg "No pidfile found. Cannot stop ${DAEMON}" 5
    fi
    ;;
  restart)
    if ${0} stop
    then
        ${0} start
    fi
    ;;
  status)
    printdaemonstatus
    ;;
  *)
    echo "Usage: $N {start|stop|force-stop|restart|status}" >&2
    exit 1
    ;;
esac

exit 0
