#!/usr/bin/env perl

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

# 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 for unavailable back ends.
Such back ends are taken offline. This is repeated each 'period' seconds.

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} };
    for my $b (@backends) {
        print("Back end ", $b->{nr}, " at ", $b->{address},
              ": available=", $b->{available}, " up=", $b->{up}, "\n");
        if ($b->{available} ne 'available' and $b->{up} eq 'up') {
            print("  Marking back end as 'down'.\n");
            my $resp = $ua->get($url . '/backend/' . $b->{nr} . '/up/0');
            warn("Failed to mark back end down: ", $resp->status_line(), "\n")
              unless ($resp->is_success());
        }
    }
}
    
    
