#!/bin/bash

if [ -f /etc/default/kamailio ]; then
	. /etc/default/kamailio
fi

if [ -f /etc/sysconfig/kamailio ]; then
	. /etc/sysconfig/kamailio
fi

RETVAL=1
USER=${KAMAILIO_USER:-kamailio}
GROUP=${KAMAILIO_GROUP:-kamailio}
BIN_FILE=${KAMAILIO_BIN:-/usr/sbin/kamailio}
PID_FILE=${KAMAILIO_PID:-/var/run/kamailio/kazoo-kamailio.pid}
CFG_FILE=${KAMAILIO_CONFIG:-/etc/kazoo/kamailio/kamailio.cfg}
export HOME=${KAMAILIO_HOME:-/var/run/kamailio}

SHM_MEMORY=$((`echo $SHM_MEMORY | sed -e 's/[^0-9]//g'`))
PKG_MEMORY=$((`echo $PKG_MEMORY | sed -e 's/[^0-9]//g'`))
[ $SHM_MEMORY -le 0 ] && SHM_MEMORY=64
[ $PKG_MEMORY -le 0 ] && PKG_MEMORY=8

if test "$DUMP_CORE" = "yes" ; then
	ulimit -c unlimited
fi

prepare() {
	mkdir -p /var/run/kamailio
	chown -R ${USER} /var/run/kamailio
	if [ -e ${PID_FILE} ]; then
		rm -rf ${PID_FILE}
	fi
	if [ ! -f /etc/kazoo/kamailio/db/kazoo.db ]; then
		KazooDB -init /etc/kazoo/kamailio/kazoodb.sql
	fi
        chown -R ${USER} /etc/kazoo/kamailio/db
	RETVAL=$?
}

start() {
	cd ${HOME}

	check_config
	check_fork

	if [ "$(whoami)" == "${USER}" ]; then
		set -- ${BIN_FILE} -f ${CFG_FILE} -m ${SHM_MEMORY} -M ${PKG_MEMORY} ${EXTRA_OPTIONS} "$@"
		exec "$@"
	else
		set -- ${BIN_FILE} -f ${CFG_FILE} -m ${SHM_MEMORY} -M ${PKG_MEMORY} -u ${USER} -g ${GROUP} ${EXTRA_OPTIONS} "$@"
		runuser -s /bin/bash ${USER} -c "$*"	
	fi
	RETVAL=$?
	
	if [ ${RETVAL} -ne 0 ]; then
		echo "Failed to start Kamailio!"
		RETVAL=1
	fi
}

stop() {
	killall ${BIN_FILE}
	RETVAL=$?
}

restart() {
	stop
	start
}

reset-restart() {
	cd /etc/kazoo/kamailio/dbtext/
	stop

	head -n1 active_watchers > active_watchers.tmp 
	mv -f active_watchers.tmp active_watchers 

	head -n1 watchers > watchers.tmp
	mv -f watchers.tmp watchers 

	head -n1 presentity > presentity.tmp 
	mv -f presentity.tmp presentity 

	chown kamailio:daemon *

	start
}

status() {
	kamcmd dispatcher.list
	RETVAL=$?
}

# Do not start kamailio 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.*" $CFG_FILE; then
		echo "WARNING: fork=no specified in config file"
		exit 1
	fi
}

check_config ()
{
	local ERRORS=$($BIN_FILE -c -f ${CFG_FILE} 2>&1 > /dev/null)
	RETVAL=$?

	if [ ${RETVAL} -ne 0 ]; then
		echo "ERROR: Invalid configuration file ${CFG_FILE}!"
		echo -e "\n${ERRORS}\n"
	else
		echo "No errors found in ${CFG_FILE}"
	fi
}

case "$1" in
	prepare)
		prepare
		;;
	background)
		shift
		start $@
		;;
	start)
		shift
		start -DD $@
		;;
	stop)
		stop
		;;
	restart)
		restart
		;;
	reset-restart)
		reset-restart
		;;
	status)
		status
		;;
	check)
		check_config
		;;
	*)
		echo $"Usage: $0 {prepare|start|background|stop|restart|reset-restart|status|check|pid}"
esac

exit ${RETVAL}
