#!/bin/sh
#
# unimrcp-server This shell script takes care of starting and stopping the UniMRCP server.
#
# chkconfig: 2345 65 35
# description: UniMRCP is an open source MRCP v1 & v2 server.

# Some global variables

# Application
APP_NAME="unimrcpserver"
APP_LONG_NAME="UniMRCP Server"
UNIMRCP_DIR="/usr/local/unimrcp/"
DAEMON_ARGS="-d -r ${UNIMRCP_DIR}"
APP_ARGS="-o 2"

EXEC="${UNIMRCP_DIR}bin/${APP_NAME}"

# sudo user
USERNAME=root

# Priority at which to run the server. See "man nice" for valid priorities.
# nice is only used if a priority is specified.
PRIORITY=

# Location of the pid file.
PIDDIR="/var/run/"
pid=

if [ -e $PIDDIR ]; then
    echo
else
    mkdir $PIDDIR
fi

# Allow configuration overrides in /etc/sysconfig/$APP_NAME
CONFIGFILE=/etc/sysconfig/$APP_NAME

[ -x $CONFIGFILE ] && . $CONFIGFILE

# Do not modify anything beyond this point
#-----------------------------------------------------------------------------

# Get the fully qualified path to the script
case $0 in
    /*)
        SCRIPT="$0"
        ;;
    *)
        PWD=`pwd`
        SCRIPT="$PWD/$0"
        ;;
esac

# Change spaces to ":" so the tokens can be parsed.
SCRIPT=`echo $SCRIPT | sed -e 's; ;:;g'`
# Get the real path to this script, resolving any symbolic links
TOKENS=`echo $SCRIPT | sed -e 's;/; ;g'`
REALPATH=
for C in $TOKENS; do
    REALPATH="$REALPATH/$C"
    while [ -h "$REALPATH" ] ; do
        LS="`ls -ld "$REALPATH"`"
        LINK="`expr "$LS" : '.*-> \(.*\)$'`"
        if expr "$LINK" : '/.*' > /dev/null; then
            REALPATH="$LINK"
        else
            REALPATH="`dirname "$REALPATH"`""/$LINK"
        fi
    done
done
# Change ":" chars back to spaces.
REALPATH=`echo $REALPATH | sed -e 's;:; ;g'`

# Change the current directory to the location of the script
cd "`dirname "$REALPATH"`"

chown $USERNAME $PIDDIR

# Process ID
PIDFILE="$PIDDIR/$APP_NAME.pid"

# Resolve the location of the 'ps' command
PSEXE="/usr/bin/ps"
if [ ! -x $PSEXE ]
then
    PSEXE="/bin/ps"
    if [ ! -x $PSEXE ]
    then
        echo "Unable to locate 'ps'."
        echo "Please report this with the location on your system."
        exit 1
    fi
fi

# Build the nice clause
if [ "X$PRIORITY" = "X" ]
then
    CMDNICE=""
else
    CMDNICE="nice -$PRIORITY"
fi

getpid() {
    if [ -f $PIDFILE ]
    then
        if [ -r $PIDFILE ]
        then
            pid=`cat $PIDFILE`
            if [ "X$pid" != "X" ]
            then
                # Verify that a process with this pid is still running.
                pid=`$PSEXE -p $pid | grep $pid | grep -v grep | awk '{print $1}' | tail -1`
                if [ "X$pid" = "X" ]
                then
                    # This is a stale pid file.
                    rm -f $PIDFILE
                    echo "Removed stale pid file: $PIDFILE"
                fi
            fi
        else
            echo "Cannot read $PIDFILE."
            exit 1
        fi
    fi
}

testpid() {
    pid=`$PSEXE -p $pid | grep $pid | grep -v grep | awk '{print $1}' | tail -1`
    if [ "X$pid" = "X" ]
    then
        # Process is gone so remove the pid file.
        rm -f $PIDFILE
    fi
}

console() {
    echo "Running $APP_LONG_NAME..."
    getpid
    if [ "X$pid" = "X" ]
    then
        exec sudo -u $USERNAME $CMDNICE $EXEC $APP_ARGS
        echo $pid > $PIDFILE
    else
        echo "$APP_LONG_NAME is already running."
        exit 1
    fi
}

start() {
    echo "Starting $APP_LONG_NAME..."
    getpid
    if [ "X$pid" = "X" ]
    then
        sudo -u $USERNAME $CMDNICE $EXEC $DAEMON_ARGS $APP_ARGS
        pid=`$PSEXE -C $APP_NAME -o pid=`
        echo $pid > $PIDFILE
    else
        echo "$APP_LONG_NAME is already running."
        exit 1
    fi
}

stopit() {
    echo "Stopping $APP_LONG_NAME..."
    getpid
    if [ "X$pid" = "X" ]
    then
        echo "$APP_LONG_NAME was not running."
    else
         # Running so try to stop it.
        sudo -u $USERNAME kill $pid
        if [ $? -ne 0 ]
        then
            # An explanation for the failure should have been given
            echo "Unable to stop $APP_LONG_NAME."
            exit 1
        fi

        # We can not predict how long it will take for the wrapper to
        # actually stop as it depends on settings in wrapper.conf.
        # Loop until it does.
        savepid=$pid
        CNT=0
        TOTCNT=0
        while [ "X$pid" != "X" ]
        do
            # Loop for up to 5 minutes
            if [ "$TOTCNT" -lt "300" ]
            then
                if [ "$CNT" -lt "5" ]
                then
                    CNT=`expr $CNT + 1`
                else
                    echo "Waiting for $APP_LONG_NAME to exit..."
                    CNT=0
                fi
                TOTCNT=`expr $TOTCNT + 1`

                sleep 1

                testpid
            else
                pid=
            fi
        done

        pid=$savepid
        testpid
        if [ "X$pid" != "X" ]
        then
            echo "Timed out waiting for $APP_LONG_NAME to exit."
            echo " Attempting a forced exit..."
            kill -9 $pid
        fi

        pid=$savepid
        testpid
        if [ "X$pid" != "X" ]
        then
            echo "Failed to stop $APP_LONG_NAME."
            exit 1
        else
            echo "Stopped $APP_LONG_NAME."
        fi
    fi
}

status() {
    getpid
    if [ "X$pid" = "X" ]
    then
        echo "$APP_LONG_NAME is not running."
        exit 1
    else
        echo "$APP_LONG_NAME is running ($pid)."
        exit 0
    fi
}

case "$1" in

    'console')
        console
        ;;

    'start')
        start
        ;;

    'stop')
        stopit
        ;;

    'restart')
        stopit
        start
        ;;

    'status')
        status
        ;;

    *)
        echo "Usage: $0 { console | start | stop | restart | status }"
        exit 1
        ;;
esac

exit 0
