#! /usr/bin/perl -w
#
# Jabber bot to watch buddy online status.
#
# 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.
#
#
# How it works:
#
#   Buddies of USERNAME who are online and available will have a file
#   created and maintained in NOTIFY_DIR. The presence and timestamp
#   of the file can then be tested against in order to change the
#   way that Nagios notifications are sent (eg to send a notification
#   via Jabber/XMPP rather than SMS if a buddy is available. Saves
#   money and annoying beeps!).
#
#
#
# How to install/use:
#
# 1) Assumptions:
#    a) You already have a working setup to send notifications via SMS;
#    b) You already have a working setup to send notifications via Jabber/XMPP;
#
# 2) Copy the wrapper script 'notify_via_jabber_or_sms' to your Nagios
#    server. Modify the script to suit your environment. Modify
#    your Nagios configuration to send SMS notifications via this
#    script rather than directly via your SMS notification script (NB:
#    the wrapper script will take different arguments!)
#
#    ##### TEST THAT YOUR SMS NOTIFICATIONS STILL WORK #####
#
# 3) Register a Jabber/XMPP user USERNAME with your Jabber/XMPP
#    server using your IM client;
#
# 4) For all people that will be receiving notifications, have them
#    add USERNAME as a buddy. Authorise their addition. They should also
#    configure their IM client to automatically set their status to away if
#    idle for more than 5 or so minutes based on X/keyboard usage.
#
# 5) On your Nagios server ensure that Perl is installed and that
#    Net::XMPP is installed (libnet-xmpp-perl package on Debian or
#    use CPAN).
#
# 6) Install this script:
#     a) Copy this script to your Nagios server /usr/local/sbin/jabber_watcher
#     b) Create an account in order to run this script (or reuse your nagios login)
#     c) chmod 600 /usr/local/sbin/jabber_watcher
#     d) chown SOMEUSER:SOMEUSER /usr/local/sbin/jabber_watcher
#     e) Modify the script settings below to suit your environment;
#     f) mkdir NOTIFY_DIR. Change the ownership/permissions as appropriate.
#     f) chmod 500 /usr/local/sbin/jabber_watcher
#     g) Modify your OS startup scripts to run it on startup (don't run it as root!);
#        If you use cfengine you may want to add a configuration fragment like:
#
#    processes:
#            nagios_server:: "jabber_watcher"
#                              restart "/bin/sh -c '/usr/local/sbin/jabber_watcher &'"
#                              owner=nagios
#                              group=nagios
#                              useshell=dumb
#
# 7) Run the script! If the script is connecting to your Jabber/XMPP
#    server properly, then you should see files get created for each
#    of the online buddies in NOTIFY_DIR. Test that it works by changing your
#    availability status and watching the files magically disappear!
#
# 8) Test that your Nagios notifications are now getting diverted
#    to Jabber rather than SMS!

use Net::XMPP;
use strict;

use constant SERVER    => 'your.jabber.host';
use constant PORT      => 5222;
use constant USERNAME  => 'nagios';
use constant PASSWORD  => 'password';
use constant RESOURCE  => 'jabber_watcher';
use constant NOTIFY_DIR => '/var/lib/nagios-buddies-available';

$SIG{HUP} = \&Stop;
$SIG{KILL} = \&Stop;
$SIG{TERM} = \&Stop;
$SIG{INT} = \&Stop;

my $Con;

# Check paths.
if (! -d NOTIFY_DIR) {
	mkdir NOTIFY_DIR, 0700 or
	    die "ERROR: Unable to mkdir  '" . NOTIFY_DIR . "'\n";
}
chdir NOTIFY_DIR or die "ERROR: Unable to chdir to '" . NOTIFY_DIR . "'\n";

EventHandler();

sub ConnectClient
{
	$Con = new Net::XMPP::Client();

	$Con->RosterDB();
	$Con->PresenceDB();

	my $status = $Con->Connect(hostname => SERVER, port => PORT);
	if (!(defined($status)))
	{
	    print STDERR "ERROR: Jabber server is down or connection was not allowed.\n";
	    print STDERR "        ($!)\n";
	    $Con = undef;
	    return;
	}

	my @result = $Con->AuthSend(username => USERNAME,
				    password => PASSWORD,
				    resource => RESOURCE);
	if ($result[0] ne "ok")
	{
	    print STDERR "ERROR: Authorisation failed: $result[0] - $result[1]\n";
	    exit(2);
	}

	$Con->PresenceSend();
	$Con->RosterRequest();
}

sub EventHandler
{
	while(1) {
		ConnectClient();

		while(defined($Con) && defined($Con->Process(60))) {

			foreach my $jid ($Con->RosterDBJIDs()) {
				UpdateUserStatus($jid);
			}
		}

		print STDERR "ERROR: The connection was killed...\n";
		sleep 30;
	}
}

sub Stop
{
    $Con->Disconnect();
    exit(0);
}

sub UpdateUserStatus
{
	my ($jid) = @_;

	# Get username.
	my $username = $jid->GetUserID();
	$username =~ s:/,::g;

	if (IsOnline($jid)) {
		open(TMP, '>>', $username) or warn "ERROR: Unable to open file '$username'\n";
		close(TMP);
		utime(undef, undef, $username) or warn "ERROR: Unable to update timestamp of '$username'\n";
	} elsif (-f $username) {
		unlink($username) or warn "ERROR: Unable to delete presence status for '$username'\n";
	}
}

sub IsOnline
{
	my ($jid) = @_;
	my $Pres = $Con->PresenceDBQuery($jid);

	if (!(defined($Pres))) {
		return 0;
	}

	my $show = $Pres->GetShow();
	if ($show) {
		# Idle, or away, or dnd, etc.
		return 0;
	}

	return 1;
}
