#!/usr/bin/env perl

use strict;
use XML::Simple;
use LWP::UserAgent;

# Check arguments
if ($#ARGV != 1) {
    die << "ENDUSAGE";

Usage:   $0 webinterface-url period
Example: $0 http://localhost:20001 5

The XR web interface at the stated URL is checked and the back end states
are reported.

ENDUSAGE
}

# Process
while (1) {
    check($ARGV[0]);
    sleep($ARGV[1]);
}

# Check the web interface. Take unavailable back ends offline.
sub check($) {
    my $url = shift;

    # Access web interface
    my $ua = LWP::UserAgent->new();
    my $resp = $ua->get($url);
    if (! $resp->is_success()) {
	warn("Failed to access the XR web interface on '$url': ",
	     $resp->status_line(), "\n");
	return;
    }

    # Parse the XML
    my $xml;
    eval {
	$xml = XMLin($resp->content());
    };
    if ($@) {
	warn("Failed to parse web interface response: $@\n");
	return;
    }

    # print Dumper $xml;

    my @backends = @{ $xml->{backend} };
    print("\n", scalar(localtime()), "\n");
    for my $b (@backends) {
	print(" Back end ", $b->{nr}, " at ", $b->{address},
	      ": available=", $b->{available}, " up=", $b->{up});
	print(" DEAD") if ($b->{live} ne 'alive');
	print("\n");
    }
}
    
    
