#! /usr/local/bin/perl
eval 'exec perl -S $0 ${1+"$@"} ;' unless 1;
#
# find a dotted-decimal IP address somewhere on a line, look up its name
# and append the name to the line.
#
# if -i is given, replace the IP address inplace with as much of the
# name as fits (instead of appending it).
#
# if -I is given, replace the IP address inplace with the whole name
# even if the name doesn't "fit" in the original IP address's space.
#
# if -f is given, don't strip \.washington\.edu from the name
#
# if -g is given, all ip addresses on a line are done (not just the first)
#
# Corey Satten, corey @ cac.washington.edu, 2/13/97, 10/13/99
# http://staff.washington.edu/corey

$omit_wash = 1;		# omit .washington.edu unless -f flag given

while ($ARGV[0] =~ /^-./) {
    $_ = shift(@ARGV);
    if (/^-g$/) { $gflag = 1; next; }
    if (/^-i$/) { $inplace = 1; next; }
    if (/^-I$/) { $inplace = 2; next; }
    if (/^-f$/) { $omit_wash = 0; next; }
    die ("unknown flag");
    }

if ($ARGV[0] =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/) {
    # argument is IP addr not filename, just convert it and exit.
    $arg = pack("CCCC", $1, $2, $3, $4);
    ($name,$aliases,$addrtype,$length,@addrs) = gethostbyaddr($arg, 2);
    if ($name) {
	print "$name\n";
	exit(0);
	}
    exit(1);
    }

while (<>) {
    $tmp = $_;		# copy of input line used for ip search & loop control
    $ofs = 0;		# keep track of offset caused by long -I names

    while ($tmp =~ /(\d+)\.(\d+)\.(\d+)\.(\d+)( *)/) {
	$arg = pack("CCCC", $1, $2, $3, $4);
	if (!$cache{$arg}) {
	    ($name,$aliases,$addrtype,$length,@addrs) = gethostbyaddr($arg, 2);
	    $cache{$arg} = $name;
	    }
	else { $name = $cache{$arg}; }

	$pos = length($`);		# position IP found in original line
	$len = length("$1.$2.$3.$4$5");	# len of IP and trailing space
	$fmt = $len - 1;		# printf fmt len for name

	$name =~ s/\.washington\.edu$// if ($omit_wash);

	if ($inplace) {
	  if ($name) {
	    if ($inplace == 2) {	# untruncated names can make line grow
		$grow = length($name) > $fmt ? length($name) - $fmt : 0;
		$fmt += $grow;		# line will grow by this much
		}
	    substr($_, $pos+$ofs, $len) = sprintf("%-${fmt}.${fmt}s ", $name);
	    $ofs += $grow;		# keep track of cumulative growth
	    }
	  }
	else { s/$/	$name/; }

	last unless($gflag);

	substr($tmp, $pos, $len) = '-' x $len;	# wipe addr from loop control
	}
    print;
    }
