#!/bin/bash
# vim:textwidth=80:tabstop=4:shiftwidth=4:smartindent
#
# this scripts prompts the user thrice, then tells asterisk to please shut down,
# then kills asterisk and related processes with SIGTERM, then kills asterisk
# and related processes with SIGKILL, and then starts asterisk with
# safe_asterisk.

DELAY=1
LOGFILE=/var/log/asterisk/yesyesreallyrestartasterisknow.log
ASTERISK=/usr/sbin/asterisk
SAFE_ASTERISK=/usr/sbin/safe_asterisk

# processes to kill. Please list all AGI scripts here as well as the asterisk
# processes, since asterisk may leave them unkilled.
PROCVICTIMS="safe_asterisk asterisk mpg123 something.agi"

# helper functions
# die ["string to print"]
function die {
	if [[ "$1" != "" ]]; then
		echo $1
	else
		echo "ok. no harm done..."
	fi
	exit
}

# docmd "string to print" "cmd"
function docmd {
	printf "$1..."
	`$2 >> $LOGFILE 2>&1`
	RETCODE=$?
	sleep $DELAY
	if [[ "$RETCODE" == "0" ]]; then
		echo " OK"
	else
		echo " FAILED"
	fi
}

# prompt "string" "positive answer"
function prompt {
	printf "$1"
	read answer
	if [[ "$answer" != "$2" ]]; then
		die
	fi
}

# countdown secs
function countdown {
	echo -n "$1 "
	if [[ $1 > 0 ]]; then
		sleep 1
		countdown $[ $1 - 1 ]
	else
		echo "boom!"
	fi
}

# am I really root?
if [[ "$UID" != "0" ]]; then
	echo "Sorry, only root can do this." >&2
	exit;
fi

echo "`date`: $0 invoked" >> $LOGFILE

prompt "Are you sure you want to restart asterisk? (yes/no)? " "yes"
prompt "Really sure? (yes/no)? " "yes"
prompt "Absolutely positive? (YES/no)? " "YES"
echo "OK, I'll do it, but if you're not sure about this, press ctrl+c now."
countdown 5

# please remove the following line to allow this script to really restart
# asterisk
# die "i'm a coward";

# doing the dirty work
docmd "Asking asterisk kindly to shutdown" "$ASTERISK -rx 'stop now'"
docmd "Sending asterisk processes the TERM signal" "killall -15 $PROCVICTIMS"
docmd "Sending asterisk processes KILL signal" "killall -9 $PROCVICTIMS"
docmd "Starting safe_asterisk" "$SAFE_ASTERISK"
for i in $PROCVICTIMS
do
	ps axf | grep -w $i | grep -v grep
done
