#!/usr/local/perl/bin/perl
#
# given the hostname, addhostr will return the entire record for the user
# to view.  if a printer designated, then the output is sent to the
# printer instead of the screen.
#

sub usage {
	print("usage: addhostr host\n");
	print("usage: addhostr host postscript-printer\n");
	print("usage: addhostr \"*\" postscript-printer\n");
	exit(0);
}

split(/\//,$0);
$scriptname    = $_[$#_];
$nargs = @ARGV;           # nargs will have the number of command line arguments
$dumphost = "/usr/local/etc/dumphost";
$dumpconfig = "/tmp/dumpconfig$$";
$dumpout = "/tmp/dumpout$$";
$host = $ARGV[0];
$printer = $ARGV[1];
$report = "addhost.report";

&usage if ($host eq "");

chdir("/tmp") || die("$scriptname: could not change directory to /tmp.\n");

open(REPORT,">$report") || die("$scriptname: could not open $report.\n");

open(DUMPHOST,"| $dumphost > $dumpout") || die("$scriptname: dumphost failed.\n");
print(DUMPHOST "set hostname $host\n") || die("$scriptname: dumphost failed.\n");
print(DUMPHOST "sort a hostname\n") || die("$scriptname: dumphost failed.\n");
print(DUMPHOST "show all\n") || die("$scriptname: dumphost failed.\n");
print(DUMPHOST "pretty\n") || die("$scriptname: dumphost failed.\n");
print(DUMPHOST "match\n") || die("$scriptname: dumphost failed.\n");
print(DUMPHOST "quit\n") || die("$scriptname: dumphost failed.\n");
close(DUMPHOST);

$n = 0;
open(DUMPOUT,"<$dumpout");
while (<DUMPOUT>) {
	if ($n != 0 && $_ =~ /hostname:/io) {
		print(REPORT "\n");
	}
	print(REPORT);
	$n++;
}
close(DUMPOUT);
close(REPORT);

if ($n == 0) {
	print("$scriptname: no hosts found matching \"$host\".\n");
} elsif ($printer ne "") {
	$flags = '-2rG';
	if ($printer eq "-") {
		$printer = "-p -";
	} else {
		$printer = "-P$printer";
	}
	system("enscript $flags $printer $report");
} else {
	system("less $report");
}

unlink($dumpout,$report);
exit;
