#!/bin/sh

### BEGIN INIT INFO
# Provides:          osi-udpproxy
# 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: UDP Proxy daemon.
# Description:       UDP Proxy daemon.
### END INIT INFO

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

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

trap trap_error HUP INT ILL ABRT FPE

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

start_instance(){ # $1: index, $2: additional options
    local UDP_PROXY_ENABLED=$(eval echo \${"UDP_PROXY_ENABLED_${1}"} | tr [A-Z] [a-z] )
    # ... If not enabled, don't do anything
    if ( [ -z ${UDP_PROXY_ENABLED} ] || [ ${UDP_PROXY_ENABLED} != "yes" ] ) ; then
        return 0;
    fi
    local UDP_PROXY_HOST_FILE="/etc/3d-p/osi-udpproxy/osi-udpproxy.peers.${1}"
#     local UDP_PROXY_RELAY=$(eval echo \${"UDP_PROXY_RELAY_${1}"} | tr [A-Z] [a-z] )
    local UDP_PROXY_SRC_PORT=$(eval echo \${"UDP_PROXY_SRC_PORT_${1}"} )
    local UDP_PROXY_DST_PORT=$(eval echo \${"UDP_PROXY_DST_PORT_${1}"} )
    local UDP_PROXY_IP1=$(eval echo \${"UDP_PROXY_IP1_${1}"} )
    local UDP_PROXY_IP2=$(eval echo \${"UDP_PROXY_IP2_${1}"} )

    ARGS="${2}"
    ARGS="$ARGS peerfile=${UDP_PROXY_HOST_FILE}"
#     if [ ! -z ${UDP_PROXY_RELAY} ]; then       ARGS="${ARGS} relay=${UDP_PROXY_RELAY}"; fi
    if [ ! -z ${UDP_PROXY_SRC_PORT} ]; then    ARGS="${ARGS} sport=${UDP_PROXY_SRC_PORT}"; fi
    if [ ! -z ${UDP_PROXY_DST_PORT} ]; then    ARGS="${ARGS} dport=${UDP_PROXY_DST_PORT}"; fi
    if [ ! -z ${UDP_PROXY_IP1} ]; then         ARGS="${ARGS} ip1=${UDP_PROXY_IP1}"; fi
    if [ ! -z ${UDP_PROXY_IP2} ]; then         ARGS="${ARGS} ip2=${UDP_PROXY_IP2}"; fi

    if ! osi_udpproxy ${ARGS}; then
        echo "Error! Failed to launch: osi_udpproxy ${ARGS}" >&2
        return 1
    fi
    echo -e "\rosi-udpproxy[${1}] started."
    return 0
}

#----MAIN----

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

    . ${CONFIG_FILE}
    for i in `seq 0 $((NUM_SESSIONS-1))`; do
        UDP_PROXY_PID_FILE="/var/run/osi-udpproxy.${i}.pid"
        if [ -e ${UDP_PROXY_PID_FILE} ]; then
            if [ ! -e /proc/`cat ${UDP_PROXY_PID_FILE}` ]; then
                logger "Removing obsolete ${UDP_PROXY_PID_FILE}"
                if ! rm ${UDP_PROXY_PID_FILE}; then
                    logger "Error! Failed to remove ${UDP_PROXY_PID_FILE}"
                    exit 1
                fi
            else
                echo "Error! osi-udpproxy.${i} is already running" >&2
                exit 1
            fi
        fi
        logger "Starting instance ${i}"
        if ! start_instance ${i} "debug=off pidfile=${UDP_PROXY_PID_FILE}"; then
            echo "Error! Failed to start instance ${i}" >&2
            ${0} stop 2> /dev/null
            exit 1
        fi
    done;

	;;
debug)
    . ${CONFIG_FILE}
    if ! start_instance 0 "debug=on"; then
        echo "Error! Failed to start instance 0 in debug mode" >&2
        exit 1
    fi
	;;
stop)
    RET=0
    for i in `seq 0 $((NUM_SESSIONS-1))`; do
        UDP_PROXY_PID_FILE="/var/run/osi-udpproxy.${i}.pid"
        if [ -e ${UDP_PROXY_PID_FILE} ]; then
            logger "Killing instance ${i} with pid=`cat ${UDP_PROXY_PID_FILE}`"
            PID=`cat ${UDP_PROXY_PID_FILE}`
            if ! kill -TERM ${PID}; then
                logger "Warning! Failed to kill osi-udpproxy with pid=${PID}" >&2
            fi
        fi
        if [ -e ${UDP_PROXY_PID_FILE} ]; then
            logger "Removing ${TCP_UDP_PID_FILE}"
            if ! rm -f ${UDP_PROXY_PID_FILE}; then
                echo "Error! Failed to remove ${UDP_PROXY_PID_FILE}" >&2
                RET=1
            fi
        fi
        echo -e "\rosi-udpproxy[${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} stop 2> /dev/null
        exit 1
    fi
	;;
get_all)
    cat ${CONFIG_FILE} || exit 1
    ;;
*)
    echo "Usage: /etc/init.d/osi-udpproxy {start|stop|restart|debug}" >&2
    exit 1
esac
exit 0
