#! /bin/bash
#
# Written by Emmanuel Galanos ( <e AT lemmin . gs> )
# Copyright 2007 Anchor Systems ( http://anchor.com.au ).
# You are permitted to use this script under the same licence
# terms as Nagios.
#
# Wrapper SMS notification script to send notifications via Jabber or SMS if
# person is not available. Use this in conjunction with jabber_watcher. See
# jabber_watcher for detailed installation instructions.

NOTIFY_DIR=/var/lib/nagios-buddies-available
JABBER_SCRIPT=/usr/local/sbin/notify_via_jabber
SMS_SCRIPT=/usr/local/sbin/notify_via_sms

help() {
	echo "Usage: $0 jabber_id mobile_number message" 1>&2
	exit 1
}

notify_via_jabber() {
	local jabber_id=$1
	local message=$2

	local jabber_name=$(echo $jabber_id | cut -d@ -f1)
	local status_file="$NOTIFY_DIR/$jabber_name"

	TMPFILE=`mktemp -t timestamp.XXXXXX` || return 1
	touch -d 'now - 2 minutes' $TMPFILE || return 1

	if [ -e "$status_file" -a "$status_file" -nt "$old_file" ]
	then
		# Buddy is online.
		$JABBER_SCRIPT "$jabber_id" "$message"
		return $?
	else
		return 1
	fi
}

notify_via_sms() {
	local mobile_number=$1
	local message=$2

	$SMS_SCRIPT -n "$mobile_number" -m "$message"
	return $?
}

cleanup() {
	trap - $SIGNALS

	if [ -n "$TMPFILE" ]
	then
		rm -f "$TMPFILE"
	fi
}

# Check arguments.
if [ $# -lt 3 ]
then
	help
fi

jabber_id=$1
mobile_number=$2
message=$3

SIGNALS="EXIT"
trap cleanup $SIGNALS

notify_via_jabber "$jabber_id" "$message" || notify_via_sms "$mobile_number" "$message"
