#!/usr/bin/perl
#$Id: test_cluster.pl,v 1.7 2023/12/05 12:01:08 sqko Exp $
use strict;
use warnings;
use RFC::Main;
use HTTP::Tiny;
use Sys::Hostname;
my $check_rig = 1;
foreach (@ARGV)
{
    if ($_ =~ /--no_rig_test/)
    {
        $check_rig = 0;
    }
}

my $Client = HTTP::Tiny->new();
my @list = ();
my $hostname = hostname;
my $listserver = get_cv('servers','listserver');
if ($listserver)
{
    chomp $listserver;
    my $response = $Client->get($listserver);
    if ($response->{status} == 599)
    {
	## Try with https if 599 error (if firewall blocks normal http but not https)
	$response = $Client->get('https://'.$listserver);
    }
    if ($response->{status} == 200)
    {
	print "Getting server list from listserver $listserver\n";
	my $str= RFC::Main::report_client($listserver,'servers');
	my @l = split(/\t/,$str) if ($str && $str !~ /ERROR/);
	foreach (@l)
	{
	    if (/([\w\.\-]+)/)
	    {
		push @list,$1;
	    }
	}
	print "Recieved ".scalar(@list)." server names\n";
    }
    else
    {
	print "Listserver offline, exiting!\n";
	exit;
    }
}
print "Checking each server in turn:\n";
foreach my $s (sort @list)
{
    my $url = $s;
    my $response = $Client->get($url);
    if ($response->{status} == 599)
    {
	## Try with https if 599 error (if firewall blocks normal http but not https)
	$response = $Client->get('https://'.$url);
    }
    if ($response->{status} == 200)
    {
	print "Getting version and rigs from server $s\n";
	my $version = RFC::Main::report_client($s,'version');
	$version = 'UNKNOWN' unless defined($version);
	chomp $version;
	my $str = RFC::Main::report_client($s,'active_rigs');
	$str = '' unless defined($str);
	chomp $str;
	$str =~ s/[\s\t]+/\t/g;
	print "Version: $version, \tRigs: \t$str\n";
	next unless ($check_rig);
	$str = RFC::Main::report_client($s,'rigs');
	print "Testing data access restrictions for each rig:\n";
	chomp $str;
	$str =~ s/[\s\t]+/\t/g;
	my @rigs = split(/\t/,$str);
	foreach my $rig (@rigs)
	{
	    my $url = $s.'/rig'.$rig.'/test.nr';
	    my $response = $Client->get($url);
	    if ($response->{status} == 599)
	    {
		## Try with https if 599 error (if firewall blocks normal http but not https)
		$response = $Client->get('https://'.$url);
	    }
	    if ($response->{status} == 403)
	    {
		print "Rig $rig: Protected\n";
	    }
	    elsif ($response->{status} == 200)
	    {
		if ($s =~ /$hostname/)
		{
		    print "Rig $rig: Access restrictions can not be reliably tested from same server!\n";
		}
		else
		{
		    print "Rig $rig: Public\n";
		}
	    }
	    else
	    {
		print "Error for $url: $response->{status}\n";
	    }
	}
    }
    else
    {
	print "Server $s is not reachable, skipping..\n";
    }
}
