#!/usr/bin/perl
#
# ipad name..
#
# Find an IP address for the given name(s).   The  output  is  the  IP
# address, with no decoration, so it can easily be used in scripts. If
# we can't figure out the address, we produce nothing at all, but exit
# with  status 1 as a clue that we failed.  Note that we strip away an
# initial '#'; this is used in the network maps for name suppression.
#
# This routine should be contrasted with  the  "addr"  program,  which
# passes its command-line args to /local/bin/perlthostbyname(), and thus shows what
# the nameserver (or /etc/hosts) has for the name.
#
# The exit status is the number of failures to find IP addresses; zero
# as usual means complete success.

$stat = 0;	# Exit status
#@ndcent = /local/bin/perltpwnam('ndc');
#$ndcdir = $ENV{'NDCDIR'} || $ndcent[7] || '/ndc';
#$mondir = $ENV{'NDCMONDIR'} || "$ndcdir/mon";
#chdir $mondir if $mondir;

$ipat4 = '\d+\.\d+\.\d+\.\d+';
$ipat3 = '\d+\.\d+\.\d+';
$ipat2 = '\d+\.\d+';
$ipat1 = '\d+';

host:
for ($a = 0; $a <= $#ARGV; $a++) {
	($node = $ARGV[$a]) =~ s/^\W*//;	# Strip off Map's initial '#' and other junk.
	$ipad = 0;
	if (-f ($file = "name-ipad/$node")) {
		$f = open(F,"<$file");
	} elsif (-f ($file = "node-ipad/$node")) {
		$f = open(F,"<$file");
	} elsif (-f ($file = "host-ipad/$node")) {
		$f = open(F,"<$file");
	} elsif (-f ($file = "agnt-ipad/$node")) {
		$f = open(F,"<$file");
	}
	if ($f) {
		for (<F>) {
			if (/^\s*($ipat4)/) {
				($ipad = $1) =~ s/\s+.*//;
				print "$ipad\n";
				next host;
			}
		}
		next if ($ipad);
	}
	if ($node =~ /^$ipat4$/) {		# Is the name already an IP address?
		print "$node\n";
		next host;
	}
	if ($node =~ /^$ipat3$/) {		# Is the name a 3-term network address?
		print "$node.0\n";
		next host;
	}
	if ($node =~ /^$ipat2$/) {		# Is the name a 2-term network address?
		print "$node.0.0\n";
		next host;
	}
	if ($node =~ /^$ipat1$/) {		# Is the name a 1-term network address?
		print "$node.0.0.0\n";
		next host;
	}
	if ($ipad = `addr %D0 $node`) {
		$ipad =~ s/\s+.*//g;
		print "$ipad\n";
		next host;
	}
	$stat ++;	# Count the failures.
}
#exit $stat;
exit 0;		# Always report "success" - null value means failure.
