#!/usr/bin/sh

prefix=/usr
exec_prefix=/usr
libdir=/usr/lib64
LIBPATH=${libdir}
if [ x"$LIBPATH" != x ] ; then
    if [ x"$LD_LIBRARY_PATH" = x ] ; then
        LD_LIBRARY_PATH=$LIBPATH
    else
        LD_LIBRARY_PATH=$LIBPATH:$LD_LIBRARY_PATH
    fi
    export LD_LIBRARY_PATH
fi

#--------------------------------------------------
# usage
#
usage()
{
    (echo "Usage: $0 [options]"
     echo "Available options:"
     echo "  -help                 print this message"
     echo "  -rcssmonitor          use rcssmonitor"
     echo "  -monitor MONITOR      specify the monitor command"
    ) 1>&2
}

#--------------------------------------------------
# option
#

SERV=`which rcssserver 2> /dev/null`
if test $? -eq 1; then
    echo "Error: rcssserver can not be found in your PATH"
    echo ""
    exit 1
fi

if test $# -eq 0; then
    if test "$RCSSMONITOR"; then
        MON="$RCSSMONITOR"
        which ${MON%% *} > /dev/null 2>&1
        if test $? -eq 1; then
            echo "Error: cannot find the monitor specified by RCSSMONITOR: $RCSSMONITOR"
            echo ""
            exit 1
        fi
    else
        MON=`which rcssmonitor 2> /dev/null`
        if test $? -eq 1; then
            echo "Error: No monitors can be found in your PATH and the"
            echo "       RCSSMONITOR environment variable is not set. Please"
            echo "       add rcssmonitor or a third party monitor to you PATH,"
            echo "       or set the RCSSMONITOR environment variable to the"
            echo "       executable you wish to use."
            echo ""
            exit 1
        fi
    fi
else
    while [ $# -gt 0 ]
    do
        case $1 in
            -help)
                usage
                exit 0
                ;;

            -rcssmonitor)
                MON=`which rcssmonitor 2> /dev/null`
                if test $? -eq 1; then
                    echo "Error: rcssmonitor cannot be found in your PATH"
                    echo ""
                    exit 1
                fi
                ;;

            -monitor)
                MON="${2}"
                which ${MON%% *} > /dev/null 2>&1
                if test $? -eq 1; then
                    echo "Error: ${MON%% *} cannot be found in your PATH"
                    echo ""
                    exit 1
                fi
                shift 1
                ;;

            *)
                echo "Error: unsupported option ${1}"
                usage
                exit 1
                ;;
        esac

        shift 1
    done
fi

#--------------------------------------------------
# set handler
#

trap kill_server INT

#--------------------------------------------------
# start server
#

$SERV &
PID=$!

#--------------------------------------------------
# kill server
#
kill_server()
{
    kill -s INT $PID
    echo ""
    exit 0
}

#--------------------------------------------------
# start monitor
#

sleep 1

$MON

kill_server
