#!/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] subnet
 
  --help   This page.

  subnet   The name or IP address of the subnet in question.
 
EndOfHelp
    
    exit;

} # End if - help

$name = $ARGV[0];
$name =~ tr/A-Z/a-z/;
$host = $name;

$name = &zone_or_subnet ($name);

if (($host =~ m/^128.110.\d+$/o) || ($host =~ m/^155.99.\d+$/o)) {

    open (GREP, "/usr/bin/grep $host: $tree_root/.subnets |");

    while (<GREP>) {

	$subnet .= $_;

    }

}

$path = &zone_to_path($name);

if (-e "$path.secondary") {

    $output = "\nWe are secondary for $host.\n";
    $output .= $subnet if $subnet;
    $output .= "\nTo see the data use:\n\n\tshow_secondary $host\n";
    $output .= "\nTo see the glue data use:\n\n\tshow_primary $host\n" if -e "$path.primary";

} elsif (-e "$path.soa") {

    $output = "\nWe are primary for $host\n";
    $output .= $subnet if $subnet;
    $output .= "\nTo see the data use:\n\n\tshow_soa $host\n\tshow_primary $host\n";

} elsif (-e "$path.primary") {

    $output = "\nWe are primary for $host\n";
    $output .= $subnet if $subnet;
    $zone = "$name.";
    $zone =~ s/^[^\.]+\.//o;
    $path = &zone_to_path ($zone);

    FIND_SOA: while ($zone) {

	if (-e "$path.soa") {

	    $output .= "SOA record is in zone $zone\n";
	    last FIND_SOA;

	} else {

	    $zone =~ s/^[^\.]+\.//o;
	    $path = &zone_to_path ($zone);

	}

    }

    $output .= "Warning: no SOA for $name can be found in any parent zone\n" unless $zone;
    $output .= "\nTo see the data use:\n\n";
    $output .= "\tshow_soa $zone\n" if $zone;
    $output .= "\tshow_primary $host\n";

} else {

    $output = "\nWe currently do not do name service for $host\n";
    $output .= $subnet if $subnet;

}


print "$output\n" if $output;

exit;

