#!/bin/bash
#
#       /etc/rc.d/init.d/freeswitch
#
#       The FreeSwitch Open Source Voice Platform
#
#  chkconfig: - 89 14
#  processname: freeswitch
#  config: /opt/freeswitch/conf/freeswitch.conf
#  pidfile: /opt/freeswitch/log/freeswitch/pid
#


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

# Source options file
if [ -f /etc/sysconfig/freeswitch ]; then
	. /etc/sysconfig/freeswitch
fi

prog=freeswitch
pidfile=/opt/freeswitch/log/freeswitch.pid
FS_USER=freeswitch
lockfile=/var/lock/subsys/freeswitch
RETVAL=0

# <define any local shell functions used by the code that follows>

start() {
        echo -n "Starting $prog: "
        if [ -e $lockfile ]; then
            if [ -e $pidfile && [ -e /proc/`$pidfile` ]; then
                echo -n $"cannot start freeswitch: freeswitch is already running.";
                failure $"cannot start freeswitch: freeswitch already running.";
                echo
                return 1
            fi
        fi

        daemon --user $FS_USER --pidfile $pidfile $prog $FREESWITCH_ARGS
	RETVAL=$?
        [ $RETVAL -eq 0 ] && touch $lockfile;
        return $RETVAL
}

stop() {
        echo -n "Shutting down $prog: "
        if [ ! -e $lockfile ]; then
            echo -n $"cannot stop $prog: $prog is not running."
            failure $"cannot stop $prog: $prog is not running."
            echo
            return 1;
        fi
	/opt/freeswitch/bin/freeswitch -stop
        killproc freeswitch
	RETVAL=$?
	echo
	[ $RETVAL -eq 0 ] &&  rm -f $lockfile;
        return $RETVAL
}

rhstatus() {
	status $prog;
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    status)
        status $prog
	RETVAL=$?
        ;;
    restart)
        stop
        start
        ;;
    reload)
#        <cause the service configuration to be reread, either with
#        kill -HUP or by restarting the daemons, in a manner similar
#        to restart above>
        ;;
    condrestart)
        [ -f $pidfile ] && restart || :
	;;
    *)
        echo "Usage: $prog {start|stop|status|reload|restart"
        exit 1
        ;;
esac
exit $RETVAL