#!/usr/bin/perl
# Hobbit / Xymon plugin to monitor the GNU Gatekeeper (http://www.gnugk.org/)
# Author: Jan Willamowius, jan@willamowius.de, http://www.willamowius.com
use strict;
use warnings;
use Net::Telnet;

my $color = 'green';
my $summary = 'ok';
my $status_port = 7000;
my $ip = '127.0.0.1';
my $message = '';

my $BBHOME = $ENV{BBHOME};
if(open(CONF, "$BBHOME/etc/hobbit-gnugk.cfg")) {
    my $line;
    while($line = <CONF>) {
        if($line =~ /^port(\s+|=)(.+)$/) {
            $status_port = $2;
        }
        elsif($line =~ /^ip(\s+|=)(.+)/) {
            $ip = $2;
        }
    }
    close(CONF);
}

my $con = new Net::Telnet;
$con->errmode('return');
my $ok = $con->open(Host=> $ip, Port => $status_port);
if (! $ok) {
	$color = "red";
	$message .= "$ip:$status_port\n" . $con->errmsg() . "\n";
} else {
	# TODO: add support for password auth
	$con->waitfor("/;/");
	my @data = $con->cmd(String => "Statistics", Prompt => "/;/", Timeout => 3);
	if (@data) {
		$message .= "$ip:$status_port\n@data\n";	
	} else {
		$color = "yellow" unless $color eq "red";
		$message .= "$ip:$status_port\n Timed out reading data\n";
	}
	$con->close();
}

if ($color eq "green") {
	$summary = "GnuGk OK";
} else {
	$summary = "GnuGk Not OK";
}

system('$BB $BBDISP "status $MACHINE.gnugk ' . "$color " . localtime() . "\n\n$summary\n\n$message\n\"");

exit(0);

