#!/bin/bash

NAME=asterisk
USER=asterisk
GROUP=asterisk
RUNDIR=/var/run/$NAME
PIDFILE=$RUNDIR/$NAME.pid
STARTCMD="(cd /; /usr/sbin/asterisk -G $GROUP -U $USER)"
STOPCMD="/usr/sbin/asterisk -r -x 'core stop now'"
STOPGRACECMD="/usr/sbin/asterisk -r -x 'core stop gracefully'"
STOPTIMEOUT=300

case $1 in
start)
	[ -n "$RUNDIR" ] && (install -d -m 755 -o $USER $RUNDIR || exit 1)
	if [ -f $PIDFILE ]; then
		pid=$(< $PIDFILE)
		if [ ! -d /proc/$pid ]; then
			echo "$NAME: removing stale pidfile $PIDFILE" >&2
			rm -f $PIDFILE
		fi
	fi
	if [ -f $PIDFILE ]; then
		echo "$NAME already running with pid $pid" >&2
		exit 1
	fi
	eval "$STARTCMD"
	;;
stop|stopnice)
	if [ -f $PIDFILE ]; then
		pid=$(< $PIDFILE)
		if [ ! -d /proc/$pid ]; then
			echo "$NAME: removing stale pidfile $PIDFILE" >&2
			rm -f $PIDFILE
		else
			if [ "$1" == "stop" ]; then
				eval "$STOPCMD"
			else
				eval "$STOPGRACECMD"
			fi
			t=$(printf '%(%s)T' -1)
			tend=$((t+STOPTIMEOUT))
			while [ -d /proc/$pid -a $t -lt $tend ]; do
				sleep 0.5
				t=$(printf '%(%s)T' -1)
			done
			if [ -d /proc/$pid ]; then
				echo "$NAME still running with pid $pid" >&2
				exit 1
			else
				rm -f $PIDFILE
			fi
		fi
	else
		echo "$NAME is not running" >&2
	fi
	exit 0
	;;
restart)
	$0 stop && \
	$0 start
	;;
restartnice)
	$0 stopnice && \
	$0 start
	;;
*)
	echo "usage: $0 [start|stop|stopnice|restart|restartnice]"
	;;
esac
