#! /bin/sh
### BEGIN INIT INFO
# Provides:          asterisk
# Required-Start:    $local_fs $remote_fs
# Required-Stop:     $local_fs $remote_fs
# Should-Start:      $time $network $syslog mysql iptables firehol shorewall ipmasq arno-iptables-firewall
# Should-Stop:       $network $syslog mysql iptables firehol shorewall ipmasq arno-iptables-firewall
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start/stop asterisk
# Description:       Start/stop asterisk PBX.
### END INIT INFO

# Walter Doekes, 2012.

PATH=/sbin:/bin:/usr/sbin:/usr/bin
NAME=safe_asterisk
DESC="Asterisk PBX"
AST_USER=asterisk
AST_DAEMON=/usr/local/sbin/asterisk
AST_WRAPPER=/usr/local/sbin/safe_asterisk

if ! [ -x $AST_DAEMON -a -x $AST_WRAPPER ] ; then
    echo "ERROR: $AST_DAEMON (and/or $AST_WRAPPER) not found"
    exit 0
fi

# Use the LSB standard functions for services management
. /lib/lsb/init-functions

case "$1" in
    start)
	log_begin_msg "Starting $DESC: $NAME"
	$AST_WRAPPER
	log_end_msg $?
	;;
    stop)
	log_begin_msg "Stopping $DESC: $NAME"
	# Ask asterisk to stop nicely
        $AST_DAEMON -nrx 'core stop now' >/dev/null 2>/dev/null & # (bg it)
	# Wait for it to stop completely
        stopped=0
        for x in `seq 25`; do
	    sleep 0.2
	    if ! pgrep -u$AST_USER -xf "$AST_DAEMON -f" >/dev/null; then
		stopped=1
		break
	    fi
	    echo -n .
        done
	# If it wasn't stopped completely, kill it with more force
        if [ $stopped -eq 0 ]; then
            pkill -xf "/bin/sh $AST_WRAPPER"
	    pkill -9 -u$AST_USER -xf "$AST_DAEMON -f"
	    sleep 0.2
	    echo -n killed
        fi
	# Foreground our core stop now process
	wait
        log_end_msg 0
        ;;
    reload)
	echo "Reloading $DESC configuration files."
        $AST_DAEMON -nrx 'module reload' > /dev/null 2> /dev/null
        ;;
    restart|force-reload)
        $0 stop # stop makes sure it is stopped completely
	$0 start
	# "restart|force-reload" starts Asterisk and returns 0 even if Asterisk was stopped (as LSB expects).
        ;;
    *)
	N=/etc/init.d/$NAME
        echo "Usage: $N {start|stop|restart|reload|force-reload}" >&2
	exit 1
        ;;
esac

# vim: set syn=sh ts=8 sw=4 sts=4 noet ai:
