#!/bin/sh

### BEGIN INIT INFO
# Provides:          osi-ohiservice
# Required-Start:    $remote_fs $network
# Required-Stop:     $remote_fs $network
# Should-Start:      iep-network
# Should-Stop:       iep-network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: OHI Service daemon.
# Description:       OHI Service daemon.
### END INIT INFO

PATH=/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/bin

# ... Trapping errors and
trap_error() {
    logger "Error Occured!"
    exit 1
}

trap trap_error HUP INT ILL ABRT FPE

# ... Check for config file
CONFIG_FILE="/etc/3d-p/osi-ohiservice/osi-ohiservice"
if [ ! -e ${CONFIG_FILE} ]; then
    echo "${CONFIG_FILE} config file not found" >&2
    exit 1
fi

start_instance() { # $1 : index, $2: extra arg
    OHI_SERVICE_ENABLED=$(eval echo \${"OHI_SERVICE_ENABLED_${1}"} | tr [A-Z] [a-z] )
    # ... If not enabled, don't do anything
    if ( [ -z ${OHI_SERVICE_ENABLED} ] || [ ${OHI_SERVICE_ENABLED} = "no" ] ) ; then
        return 0;
    fi
    OHI_SERVICE_UDP_PEER_FILE="/etc/3d-p/osi-ohiservice/osi-ohiservice.peers.${1}"
    OHI_SERVICE_PORT=$(eval echo \${"OHI_SERVICE_PORT_${1}"})
    OHI_SERVICE_QLEN=$(eval echo \${"OHI_SERVICE_QLEN_${1}"})
    OHI_SERVICE_TTL=$(eval echo \${"OHI_SERVICE_TTL_${1}"})
    OHI_SERVICE_KEEP_ALIVE_TIME=$(eval echo \${"OHI_SERVICE_KEEP_ALIVE_TIME_${1}"})
    OHI_SERVICE_KEEP_ALIVE_INTERVAL=$(eval echo \${"OHI_SERVICE_KEEP_ALIVE_INTERVAL_${1}"})
    OHI_SERVICE_KEEP_ALIVE_COUNT=$(eval echo \${"OHI_SERVICE_KEEP_ALIVE_COUNT_${1}"})
    OHI_SERVICE_UDP_PEERS=$(eval echo \${"OHI_SERVICE_UDP_PEERS_${1}"})
# ... Setup args for binary
    ARGS="-f ${OHI_SERVICE_UDP_PEER_FILE}"
    if [ ! -z ${OHI_SERVICE_PORT} ]; then ARGS="${ARGS} -p ${OHI_SERVICE_PORT}"; fi
    if [ ! -z ${OHI_SERVICE_QLEN} ]; then ARGS="${ARGS} -q ${OHI_SERVICE_QLEN}"; fi
    if [ ! -z ${OHI_SERVICE_TTL} ]; then ARGS="${ARGS} -t ${OHI_SERVICE_TTL}"; fi
    if [ ! -z ${OHI_SERVICE_KEEP_ALIVE_TIME} ]; then ARGS="${ARGS} -T ${OHI_SERVICE_KEEP_ALIVE_TIME}"; fi
    if [ ! -z ${OHI_SERVICE_KEEP_ALIVE_INTERVAL} ]; then ARGS="${ARGS} -I ${OHI_SERVICE_KEEP_ALIVE_INTERVAL}"; fi
    if [ ! -z ${OHI_SERVICE_KEEP_ALIVE_COUNT} ]; then ARGS="${ARGS} -C ${OHI_SERVICE_KEEP_ALIVE_COUNT}"; fi
    ARGS="${ARGS} ${2}"
    if ! osi_ohiservice ${ARGS}; then
        echo "Error! Failed to launch osi_ohiservice ${ARGS}" >&2
        return 1
    fi
    return 0
}

#----MAIN----
case "${1}" in
start)
#     mkdir -p /tmp/3d-p
#     VERSION="`cat /usr/share/3d-p/osi-ohiservice/version`"
#     XML_FILE="/etc/3d-p/osi-ohiservice/osi-ohiservice_${VERSION}.xml"
#     ln -sf ${XML_FILE} /tmp/3d-p/osi-ohiservice_${VERSION}.xml

    . ${CONFIG_FILE}
    # ... starting the service
    for i in `seq 0 3`; do
        # ... remove PID file if the relevant process is no longer running
        OHI_SERVICE_PID_FILE="/var/run/osi-ohiservice.${i}.pid"
        if [ -e ${OHI_SERVICE_PID_FILE} ]; then
            if [ ! -e /proc/`cat ${OHI_SERVICE_PID_FILE}` ]; then
                logger "Removing obsolete ${OHI_SERVICE_PID_FILE}"
                if ! rm ${OHI_SERVICE_PID_FILE}; then
                    echo "Error! Failed to remove ${OHI_SERVICE_PID_FILE}" >&2
                    exit 1
                fi
            else
                echo "Error! osi-ohiservice.${i} is already running" >&2
                exit 1
            fi
        fi
        logger "Starting osi-ohiservice instance ${i}"
        # start the service
        if ! start_instance ${i} "--pidfile=${OHI_SERVICE_PID_FILE}"; then
            echo "Error! Failed to start instance ${i}" >&2
            ${0} stop 2> /dev/null
            exit 1
        fi
        echo -e "\rosi-ohiservice[${i}] started."
    done;
    ;;
debug)
    if ! start_instance 0 -d; then
        echo "Error! Failed to start instance 0 in debug mode" >&2
        exit 1
    fi
    ;;
stop)
    RET=0
    for i in `seq 0 3`; do
        OHI_SERVICE_PID_FILE="/var/run/osi-ohiservice.${i}.pid"
        if [ -e ${OHI_SERVICE_PID_FILE} ]; then
            logger "Killing instance ${i} with pid=`cat ${OHI_SERVICE_PID_FILE}`..."
            PID=`cat ${OHI_SERVICE_PID_FILE}`
            if ! kill -TERM ${PID}; then
                logger "Warning! Failed to kill instance ${i} with pid=${PID}"
            fi
        fi
        if [ -e ${OHI_SERVICE_PID_FILE} ]; then
            logger "Removing ${OHI_SERVICE_PID_FILE}..."
            if ! rm -f ${OHI_SERVICE_PID_FILE}; then
                echo "Error! Failed to remove ${OHI_SERVICE_PID_FILE}" >&2
                RET=1
            fi
        fi
        echo -e "\rosi-ohiservice[${i}] stopped."
    done
    exit ${RET}
    ;;
restart|force-reload)
    if ! ${0} stop; then
        echo "Error! Command failed: ${0} stop" >&2
        exit 1
    elif ! ${0} start; then
        echo "Error! Command failed: ${0} start" >&2
        ${0} 2> /dev/null
        exit 1
    fi
    ;;
get_all)
    cat ${CONFIG_FILE}
    ;;
*)
     echo "Usage: /etc/init.d/osi-ohiservice {start|stop|restart|debug}" >&2
     exit 1
     ;;
esac
exit 0
