#!/usr/local/bin/perl
#
#
# nl690.pl   simple proof-of-principle script to produce a netlist
#				for an AS in a nsfnet (as690 as-in) gated config file.
#
#
#

require "getopts.pl";
require "qradbserver.pl";

&Getopts('H:P:S:N:hed');

$host = 'toad.merit.edu';
$port = '43';
$sources = 'MERITRR,PRDB,RIPE';
$nss = '';

if ( $opt_h || !$ARGV[0] ) {
    print <<"EOF";

Usage: $0 [-h] [-H<host>] [-P<port>] [-S<sources>] [-d] [-e] [-N<nss>] <asnum>

<host>        host to query        (default $host)
<port>        port to use          (default $port)
<sources>     db sources to query  (default $sources)
-e            write 'exact' rather than preference lines
-N<nss>       only write those with m:a(nss) for this nss
-d            debug msgs

Writes routes found on as-in lines of AS690 that start
with 'from AS<asnum>', that is, routes imported to AS690
from the specified <asnum>.  

Currently only expands lines written from PRDB that look like:

    as-in: from AS19:1 accept NSF_DB{ aslist == 1:19 }

by doing query to radbserver to get all the routes with
1:19 in their dynamic netancmnt lists in the PRDB db.

Example:  $0 114 -SPRDB

EOF
    exit;
}

$fromAS = $ARGV[0];
$toAS = "690";

$nss = "($opt_N)" if ( $opt_N ); 
$port = $opt_P	  if ( $opt_P );
$sources = $opt_S  if ( $opt_S );

local(@ASInLines) = ();
local(@Routes) = ();

&OpenConnection( $host, $port );

$cmd = "s$sources";
print STDERR "Set sources cmd: '$cmd'...\n" if $opt_d;
if ( ($r = &AskServer( $cmd, *ASInLines )) == -1 ) {
	print STDERR "\n\n==> ERROR from server on set sources cmd ($cmd): $ASInLines[0]\n";
	exit -1;
}

$cmd = "eas$toAS";
print STDERR "AS query cmd: '$cmd'...\n" if $opt_d;
if ( ($r = &AskServer( $cmd, *ASInLines )) == -1 ) {
   	print STDERR "\n\n==> ERROR from server on Get-ASIn query ($cmd): $ASInLines[0]\n";
	exit -1;
}

local($pat) = '^from AS' . $fromAS . '\ ([0-9]*)(.*)'; # the \<blank> was a : before 6 oct 94
local($pref) = 0;
foreach (@ASInLines) {
	if ( /$pat/ ) {
		$pref = 100 + $1;
		$cmd = "j$1:$fromAS$nss";
		print STDERR "Routes query cmd: '$cmd'...\n" if $opt_d;
		if ( ($r = &AskServer( $cmd, *Routes )) == $qradbserverErrorReturn ) {
			print STDERR "\n\n ERROR from server on Routes-of-Metric query ($cmd): $Routes[0]\n";
			exit $qradbserverErrorReturn;
		}
		elsif ( $r == $qradbserverNoKeyReturn ) {
			print STDERR "\n Nothing found on Routes-of-Metric query ($cmd): $Routes[0]\n";
			exit $qradbserverNoKeyReturn;
		}
		else {
			foreach (@Routes) {
				while ( s/^([0-9.]*)\/([0-9]*)(\s*)// ) {
					if ( $opt_e ) {
						printf "\t%16.16s masklen %2.2s exact;\n", $1, $2;
					}	
					else {
						printf "\t%16.16s masklen %2.2s preference $pref;\n", $1, $2;
					}
				}	 
			}
			print "\n";		# end of one metric...
		}
	}
}

&CloseConnection( $host, $port );
