#!/usr/local/bin/perl
#
# client.pl
#
# simple example to show how to use use the routines
#    OpenConnection,AskServer,CloseConnection
# in qradbserver.pl, to interact with radbserver.pl.
#
# It opens a connection, then prompts user for radbserver.pl
# queries to send, then prints array of answers from AskServer.
#

@INC = ("/ra/radbserver", @INC);
#@INC = ("/f/rrdb/bin/radbserver-lib", @INC);

require "getopts.pl";
require "qradbserver.pl";	# should be in the INC path, define above

&Getopts('hdP:H:O:S:');

if ($opt_h) {
    print <<"EOF";
    Usage:  client.pl [-P<port>] [-H<host>] [-O<query>] [-S<query>:...:] [-d]

    <port>,<host> of radbserver to call (default toad.merit.edu,43)
    <query> one-shot query
	-d to debug.
    -S is special one-shot query, meant to set source and do query and
        return rcode, rmsg, and rvalue from the cmd to caller.
       in a format to read into perl vars, eg, via:
          ($r,$m,$v) = eval `./client.pl -SsRIPE:iAS-SUNET:`;
       NB: returns | where \n were returned in Answer from server.

EOF
	exit;
}

local($host) = "radb2.ra.net";
local($port) = "5042";
local(@Answer) = ();

local($ConnectionOpen) = 0;		# used by OpenConnection
local($Server) = S;				# Used by OpenConnection and AskQuery

$port = $opt_P if $opt_P;
$host = $opt_H if $opt_H;

if ( $opt_O ) {
	$r = &AskServerOnce( $opt_O, $host, $port, *Answer );
	print STDERR "Answer lines (return $r):\n" if $opt_d;
	print join('\n',@Answer), "\n";
    exit;
}

print STDERR "Try to open the connection..." if !$opt_S;
if ( &OpenConnection( $host, $port ) < 0 ) {
	print STDERR "\nError - couldn't open server!\n";
	exit -1;
}

if ( $opt_S ) {
	# special one-shot query, meant to set source and do query and
	# return rcode, rmsg, and rvalue from the cmd to caller.
	# in a format to read into perl vars, eg, via:
	#    ($r,$m,$v) = eval `./client.pl -SsRIPE:iAS-SUNET:`;
	# NB: returns | where \n were returned in Answer from server.
	local( $r, $rm, $rv ) = (0,'','');
	while ( $opt_S =~ s/^([^:]*):// ) {
		if ( ($r = &AskServer( $1, *Answer )) == $qradbserverErrorReturn ) {
			$rm =  "Error from server:", join("\n",@Answer), "\n";
		}
		elsif ( $r == $qradbserverNoKeyReturn ) {
			$rm =  "Nothing found for that key.\n";
		}
		else {
			$rv = join('|',@Answer) . "|";
		}
	}
	&CloseConnection( $host, $port );
	print "$r\n$rm\n$rv\n\n";	# why does this need \n\n at end to assign as above?
	exit;
}

print STDERR "\nCommand to send (q to quit)? ";
while ( <STDIN> ) {
	chop;
	last if $_ eq "q";
	if ( ($r = &AskServer( $_, *Answer )) == $qradbserverErrorReturn ) {
		print STDERR "\nError from server:", join("\n",@Answer), "\n";
	}
	elsif ( $r == $qradbserverNoKeyReturn ) {
		print STDERR "\nNothing found for that key.\n";
	}
	else {
		print STDERR "Answer lines:\n", join("\n",@Answer), "\n";
	}
	print STDERR "\ncmd to send? ";
}	

&CloseConnection( $host, $port );

print STDERR "\nAll done---bye.\n\n";


