#!/usr/bin/perl -w
#
# ecaccess-association-list: List the ECaccess Gateways
#
# Laurent.Gougeon@ecmwf.int - 2010-10-15

use ECMWF::ECaccess;
use Getopt::Long;
use Pod::Usage;
use Term::ReadKey;

my %opt = ( version => 0, help => 0, manual => 0, debug => 0 );

pod2usage( -noperldoc => 1, -exit => 1, verbose => 1 ) if !GetOptions(
	\%opt,
	qw(
	  version
	  help|?
	  manual
	  debug
	  )
);

# Display version if requested
die ECMWF::ECaccess->VERSION . "\n" if ( $opt{version} );

my $gatewayName = $ARGV[0];

pod2usage( -noperldoc => 1, -exit => 1, verbose => 1 ) if ( $opt{help} );
pod2usage( -noperldoc => 1, -exit => 1, verbose => 2 ) if ( $opt{manual} );

# Create the ECaccess Controler
my $ecaccess = ECMWF::ECaccess->new();
$ecaccess->setDebug( $opt{debug} );

# Get the Token (using the Certificate in $HOME)
my $token = $ecaccess->getToken();

# Get the Control Channel
my $controlChannel = $ecaccess->getControlChannel();

if ( not($gatewayName) ) {

	# Get the list of Gateways
	my $gateways = $controlChannel->getGatewayList($token);

	# Display the information for each Gateway
	foreach $gateway ( $gateways->valueof('//getGatewayListResponse/return') ) {
		printf "%-16s %-12s %s", $gateway->{version}, $gateway->{lastReport}, $gateway->{name};
		print " (off)" if not( $gateway->{active} eq 'true' );
		print "\n";
	}
}
else {

	# Get the detail for the specified Gateway
	my $gateway = $controlChannel->getGateway( $token, $gatewayName )->valueof('//getGatewayResponse/return');
	print "     Name: " . $gateway->{name} . "\n";
	print "  Version: " . $gateway->{version} . "\n";
	print "   OS/JDK: " . $gateway->{comment} . "\n";
	print "Connected: " . ( $gateway->{active} eq 'true' ? 'yes' : 'no' ) . " (since " . $gateway->{lastReport} . ")\n";
}

# Logout
$ecaccess->releaseToken($token);

__END__

=head1 NAME

ecaccess-gateway-list - List the ECaccess Gateways

=head1 SYNOPSIS

B<ecaccess-gateway-list -version|-help|-manual>

B<ecaccess-gateway-list [-debug]> B<[>I<gateway-name>B<]>

=head1 DESCRIPTION

List all the ECaccess Gateways. When a I<gateway-name> is specified
then the details for this Gateway are displayed.

=head1 ARGUMENTS

=over 8

=item I<gateway-name> (optional)

The name of the ECaccess Gateway to retrieve the details.

=back

=head1 OPTIONS

=over 8

=item B<-version>

Display version number and exits.

=item B<-help>

Print a brief help message and exits.

=item B<-manual>

Prints the manual page and exits.

=item B<-debug>

Display the SOAP messages exchanged.

=back

=head1 EXAMPLES

B<ecaccess-gateway-list>

List all the ECaccess Gateways.

B<ecaccess-gateway-list> I<ecaccess.ecmwf.int>

List the details for the ECaccess Gateway I<ecaccess.ecmwf.int>.

=head1 SEE ALSO

B<ecaccess-gateway-name>, B<ecaccess-gateway-connected>, B<ecaccess>.

=cut
