#! /bin/sh
#
# freeswitch:       Starts the freeswitch Daemon
#
# chkconfig: 345 96 02
# processname: freeswitch
# description: Freeswitch fedora init script \
# config:
# Author: gled jsun at junsun.net

# Source function library.
. /etc/init.d/functions
. /etc/sysconfig/network

PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/freeswitch/bin
DESC="FreeSwitch Voice Switching System"
NAME=freeswitch
DAEMON=/usr/local/freeswitch/bin/$NAME
DAEMON_ARGS="-nc"
PIDFILE=/usr/local/freeswitch/run/$NAME.pid

## SECURITY NOTE: To run as non-root, create a new user for FreeSWITCH and set these variables (FS_GROUP is optional).
##
FS_USER=freeswitch
FS_GROUP=freeswitch

do_setlimits() {
        ulimit -c unlimited
        ulimit -d unlimited
        ulimit -f unlimited
        ulimit -i unlimited
        ulimit -n 999999
        ulimit -q unlimited
        ulimit -u unlimited
        ulimit -v unlimited
        ulimit -x unlimited
        ulimit -s 244
        ulimit -l unlimited
        return 0
}

base=${0##*/}

do_start() {
	echo -n "starting $base: "

        if [ -n "${FS_USER}" ]; then
                DAEMON_ARGS="${DAEMON_ARGS} -u ${FS_USER}"
        fi

        if [ -n "${FS_GROUP}" ]; then
                DAEMON_ARGS="${DAEMON_ARGS} -g ${FS_GROUP}"
        fi

        do_setlimits
        $DAEMON $DAEMON_ARGS
        RETVAL=$?
        if [ $RETVAL = 0 ]; then
                success $"$base startup"
        else
                failure $"$base startup"
        fi
        echo
        return $RETVAL
}

do_stop() {
	echo -n "stopping $base: "

	# check pid file
	if [ ! -f $PIDFILE ]; then
		echo -n "$base not running..."
        	success $"$base shutdown"
		echo
		return 0;
	fi

	# loop 10 times to make sure process quit
	pid=`cat $PIDFILE`
	for i in {1..10}; do
		echo -n "."
        	$DAEMON -stop &> /dev/null
		sleep 2
		ps -p $pid &> /dev/null
		RETVAL=$?
		if [ $RETVAL -ne 0 ]; then
        		success $"$base shutdown"
			echo 
			return 0;
		fi
	done

	failure $"$base shutdown"
	echo	
        return $RETVAL
}

# See how we were called.
case "$1" in
  start)
        do_start
        ;;
  stop)
        do_stop
        ;;
  restart)
        do_stop
        do_start
        ;;
  status)
	status -p $PIDFILE $base
	;;
  *)
        echo $"Usage: $0 {start|stop|status}"
        exit 2
        ;;
esac

exit $RETVAL
