#!/bin/sh
# ask me everything: bittorf@bluebottle.com
#
# call it via cron every minute
# * * * * * /usr/local/bin/cron.freeswitch_check.sh 2>&1 

log()
{
	local message="$1"
	local option="${2:-info}"	# e.g. alert
	local file="/home/ejbw/mylog.txt"

	logger -t $0 -p daemon.$option -s "freeswitch: $message"

	[ "$option" = "alert" ] && {
		echo "$( date ) $0: freeswitch: $message" >>"$file"
	}
}

count_registrations()
{
        local bin="/usr/local/freeswitch/bin/fs_cli"
        local api_command="sofia xmlstatus profile internal reg"
        local pattern="</registration>"
        local out

        out="$( $bin -x "$api_command" | fgrep "$pattern" | wc -l )"
        out="$( echo "$out" | sed 's/[^0-9]//g' )"

	echo ${out:-0}
}

COUNT=$( count_registrations )

if [ $COUNT -eq 0 ]; then
	log "needs a restart: $COUNT regs, pid: '$( pidof freeswitch )'" alert
	/etc/init.d/freeswitch restart
	log "restarted, pid: '$( pidof freeswitch )'"
else
	log "ok - $COUNT regs"
fi

GATEWAY="$( ip address show dev ppp0 | fgrep "inet " | while read LINE; do set -- $LINE; echo $2; done )"
[ -e /tmp/GW ] && read GATEWAY_OLD </tmp/GW
[ "$GATEWAY_OLD" = "$GATEWAY" ] || {
	log "IP changed: '$GATEWAY_OLD' -> '$GATEWAY'" alert
}
echo "$GATEWAY" >/tmp/GW

exit 0
