#!/bin/bash
#
# Startup script for OpenSIPS
#
# chkconfig: 345 85 15
# description: OpenSIPS is a fast SIP Server.
#
# processname: opensips
# pidfile: /var/run/opensips.pid
# config: /etc/opensips/opensips.cfg

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

OSER=/sbin/opensips
PROG=opensips
PID_FILE=/var/run/opensips.pid
LOCK_FILE=/var/lock/subsys/opensips
RETVAL=0
DEFAULTS=/etc/default/opensips
RUN_OPENSIPS=no

EMAIL_SCRIPT=/etc/opensips/mail2.sh
EMAIL_CONF=/etc/opensips/mail.cfg
CORE_DUMP=/tmp

# Do not start opensips if fork=no is set in the config file
# otherwise the boot process will just stop
check_fork ()
{
    if grep -q "^[[:space:]]*fork[[:space:]]*=[[:space:]]*no.*" /etc/opensips/opensips.cfg; then
        echo "Not starting $DESC: fork=no specified in config file; run /etc/init.d/opensips debug instead"
        exit 1
    fi
}

check_opensips_config ()
{
        # Check if opensips configuration is valid before starting the server
        out=$($OSER -c 2>&1 > /dev/null)
        retcode=$?
        if [ "$retcode" != '0' ]; then
            echo "Not starting $DESC: invalid configuration file!"
            echo -e "\n$out\n"
            exit 1
        fi
}


start() {
	check_opensips_config
        if [ "$1" != "debug" ]; then
            check_fork
        fi
	echo -n $"Starting $PROG: "
	daemon $OSER $OPTIONS >/dev/null 2>/dev/null
	RETVAL=$?
	echo
	[ $RETVAL = 0 ] && touch $LOCK_FILE
	return $RETVAL
}

stop() {
	echo -n $"Stopping $PROG: "
	killproc $OSER
	RETVAL=$?
	echo
	[ $RETVAL = 0 ] && rm -f $LOCK_FILE $PID_FILE
}

# Load startup options if available
if [ -f $DEFAULTS ]; then
   . $DEFAULTS || true
fi

if [ "$RUN_OPENSIPS" != "yes" ]; then
    echo "OpenSIPS not yet configured. Edit /etc/default/opensips first."
    exit 0
fi


S_MEMORY=$((`echo $S_MEMORY | sed -e 's/[^0-9]//g'`))
P_MEMORY=$((`echo $P_MEMORY | sed -e 's/[^0-9]//g'`))
[ -z "$USER" ]  && USER=opensips
[ -z "$GROUP" ] && GROUP=opensips
[ $S_MEMORY -le 0 ] && S_MEMORY=32
[ $P_MEMORY -le 0 ] && P_MEMORY=4

if test "$DUMP_CORE" = "yes" ; then
    # set proper ulimit
    ulimit -c unlimited

    # directory for the core dump files
    # COREDIR=/home/corefiles
    # [ -d $COREDIR ] || mkdir $COREDIR
    # chmod 777 $COREDIR
    # echo "$COREDIR/core.%e.sig%s.%p" > /proc/sys/kernel/core_pattern
fi

OPTIONS="-P $PID_FILE -m $S_MEMORY -M $P_MEMORY -u $USER -g $GROUP -w $CORE_DUMP"


# See how we were called.
case "$1" in
	start|debug)
		start
		$EMAIL_SCRIPT "started" "service opensips" $EMAIL_CONF &
		;;
	stop)
		stop
		$EMAIL_SCRIPT "stoped" "service opensips" $EMAIL_CONF &
		;;
	status)
		status $OSER
		RETVAL=$?
		;;
	restart)
		stop
		start
		$EMAIL_SCRIPT "restarted" "service opensips" $EMAIL_CONF &
		;;
	condrestart)
		if [ -f $PID_FILE ] ; then
			stop
			start
		fi
		;;
	*)
		echo $"Usage: $PROG {start|stop|restart|condrestart|status|debug|help}"
		exit 1
esac

exit $RETVAL