#!/bin/bash
#
# chkconfig: 35 90 12
# description: socat startup for xFOCE
#
# pidfile: /var/lock/subsys/socatd-mv0
# Get function from functions library

# Ubuntu
#INIT_FUNCS="/lib/lsb/init-functions"
# Angstrom
INIT_FUNCS="/etc/init.d/functions"

# load initd functions
. ${INIT_FUNCS}

SOCATD_INST="socatd-cn"
SOCATD_DEVICE="134.89.91.7"
SOCATD_PORT="10001"
SOCATD_ID="CN"

OPTIONS="pty,link=/dev/tty${SOCATD_ID},user=root,group=dialout,mode=664,,min=0,time=0,nonblock=1,clocal=0,ignoreeof tcp4:${SOCATD_DEVICE}:${SOCATD_PORT}"

socatd="${SOCATD-/usr/local/bin/socat}"
prog=socat
pidfile=/var/run/${SOCATD_INST}.pid
lockfile=/var/lock/subsys/${SOCATD_INST}
RETVAL=0
STOP_TIMEOUT=${STOP_TIMEOUT:-10}
# some versions of killproc support a timeout
#KILLP_OPTS="-p ${pidfile} -d ${STOP_TIMEOUT}"
KILLP_OPTS="-p ${pidfile}"


# Start the service socat
start() {
    echo -n $"Starting ${SOCATD_INST}: "

    ### create PID file
    touch $pidfile

    ### run the service
    $socatd ${OPTIONS} &

    RETVAL=$?
    PID=$!

    ### Create the lock file ###
    [ $RETVAL = 0 ] && touch ${lockfile}

    ### write PID
    echo $PID > $pidfile

    echo "success ${SOCATD_INST} server startup"
    echo
    return $RETVAL
}

# Restart the service
stop() {
    echo -n $"Stopping ${SOCATD_INST} : "

    ### stop service
    killproc ${KILLP_OPTS}
    RETVAL=$?

    ### delete the lock file ###
    [ $RETVAL = 0 ] && rm -f ${lockfile} ${pidfile}
    echo
    return $RETVAL
}
### main logic ###
case "$1" in
    start)
        start
    ;;
    stop)
        stop
    ;;
    status)
        status -p ${pidfile} $httpd
        RETVAL=$?
    ;;
    restart|reload|condrestart)
        stop
        start
    ;;
    *)
        echo $"Usage: $0 {start|stop|restart|reload|status}"
    exit 1
esac
exit 0
