#!/usr/bin/perl

open (STDERR, ">&STDOUT");
select ((select(STDOUT), $| = 1)[0]); # Synchronize STDOUT
select ((select(STDERR), $| = 1)[0]); # with STDERR

($dns_lib = $0) =~ s:(^|/)[^/]*$::;
($script=$0) =~ s:^.*/([^/]*)$:$1:;	# Get the simple name of this script.

push (@INC, $dns_lib);

require 5.0;
require 'dns_lib.perl';

use Getopt::Long;
$Getopt::Long::autoabbrev=1;    # Allow keyword abbreviations (to uniqueness).
$Getopt::Long::getopt_compat=1; # Allow both "--foo=bar" and "+foo=bar" style.
#$Getopt::Long::option_start='(--|-|\+)';       # [Use the defaults]
#$Getopt::Long::order=$Getopt::Long::REQUIRE_ORDER; # Options can't intermingle
$Getopt::Long::order=$Getopt::Long::PERMUTE;    # or options may intermingle.
$Getopt::Long::ignorecase=1;    # Don't consider case in options.
$Getopt::Long::debug=0;         ### Debug ###

$opt_help = ($#ARGV < 0);

&GetOptions ('help') || die "\nTry: $script --help for more information.\n\n";

if ($opt_help) { 
 
    print <<"EndOfHelp";
Usage: $script [OPTION] [host|ip]
 
  --help   This page.

  host|ip  The fully qualified DNS name or the IP address of the host
           you want to display
 
EndOfHelp
    
    exit;

} # End if - help

push (@lookup, $ARGV[0]);
$recurse = 1;

LOOKUP_LOOP: while ($name = shift (@lookup)) {

    if ($name =~ m/^(\d{1,3}\.*)+(in-addr\.arpa\.*)*$/o) {

	$name = &verify_ip ($name);
	$name = &reverse_ip($name) if $name !~ m/\.in-addr.arpa\.*$/o;

    } else {

	$name = &verify_name ($name);

    }

    $soa_path = &zone_to_path ($name);

    if ((($x = &verify_zone ($name)) eq 'PRIMARY') || ($x eq 'SEC_W_GLUE')) {

	$host = '@';
	$zone = $name;

    } else {

	($host, $zone) = split ('\.', $name, 2);

	if ((($x = &verify_zone ($zone)) ne 'PRIMARY') && ($x ne 'SEC_W_GLUE')) {

	    $output .= "\nNo data on host: $name\n";
	    next LOOKUP_LOOP;

	}

    }

    @file = &read_file ($zone, '.primary');
    @recs = &find_record (&build_record ($host, '', '', ''), @file);

    if ($#recs >= 0) {

	$data_found = 1;
	$output .= "\nData for $name:\n\n";

	foreach $rec (@recs) {

	    $output .= "$rec";
	    chomp ($rec);
	    if (($recurse) && ($rec =~ m/^\S+\s+IN\s+A\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/)) {

		push (@lookup, $1);

	    } elsif (($recurse) && ($rec =~ m/^\S+\s+IN\s+PTR\s+(.+\.)$/)) {

		push (@lookup, $1);

	    }

	}

    } else {

	$output .= "\nNo data on host: $name\n";

    }

    $recurse = 0;

}

print "$output\n";

exit;

