#!/bin/sh
#
# elastix-red5		Starts and stop the Red5 Flash Server (Elastix repackaging)
#
# chkconfig: 345 99 1
# description: Red5 is an open-source Flash Video server written in Java

PATH="/sbin:/bin:/usr/bin:/usr/sbin"
RETVAL=0

# Check that we are root ... so non-root users stop here.
[ "`id -u`" = 0 ] || exit 1

# Ease interaction with existing Elastix code
RED5_USER="asterisk"
RED5_PIDFILE="/var/run/red5.pid"

# Red5 startup script requires this
RED5_HOME=/opt/red5
RED5_RUN_CMD=$RED5_HOME/red5.sh
RED5_LOGDIR=$RED5_HOME/log

# Source function library
. /etc/rc.d/init.d/functions 

start()
{
	OLD_PWD=`pwd`
	cd $RED5_HOME

	echo -n "Starting Red5:"
	rm -f log/red5-output.log
	su -s /bin/sh -c "nohup $RED5_RUN_CMD > $RED5_LOGDIR/red5-output.log 2>&1 &" $RED5_USER
        RETVAL=$?
        PID=`ps ax --width=1000 | grep red5 | grep Bootstrap | awk '{print $1}'`

        if [ $RETVAL -eq 0 -a ! -z "$PID" -a ! -z "$RED5_PIDFILE" ]; then
                echo $PID > $RED5_PIDFILE
        fi

        echo

        [ $RETVAL -eq 0 -a -d /var/lock/subsys ] && touch /var/lock/subsys/red5

        sleep 1 # allows prompt to return

	cd $OLD_PWD
}

stop()
{
        OLD_PWD=`pwd`
        cd $RED5_HOME

        # Stop daemons.
        echo -n "Shutting down red5: "

	su -s /bin/sh -c "$RED5_HOME/red5-shutdown.sh"
        RETVAL=$?
        echo

        [ $RETVAL -eq 0 -a -f "$RED5_PIDFILE" ] && rm -f $RED5_PIDFILE
        [ $RETVAL -eq 0 -a -f "/var/lock/subsys/red5" ] && rm -f /var/lock/subsys/red5

	cd $OLD_PWD
}

restart() {
        stop
        sleep 10 # give it a few moments to shut down
        start
}

# Handle how we were called.
case "$1" in
        start)
                start
                ;;
        stop)
                stop
                ;;
        restart)
                restart
                ;;
        reload)
                restart
                ;;
        *)
                echo "Usage $0 {start|stop|restart|reload}"
                RETVAL=1
esac

exit $RETVAL

