#!/usr/bin/perl

open (STDERR, ">&STDOUT");
select ((select(STDOUT), $| = 1)[0]); # Syncronize 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 ###
 
&GetOptions ('help', 'warn', 'fix') || die "\nTry: $script --help for more information.\n\n";
 
if ($opt_help) { 
 
    print <<"EndOfHelp";
Usage: $script [OPTION]
 
  --help   This page.
  --warn   Show warnings also.
  --fix    Attempt to move NS records to proper .primary files
 
EndOfHelp
    
    exit;
 
} # End if - help

@dirs = ();
push (@dirs, $tree_root);

while ($current = pop (@dirs)) {

    $zone = $current;
    $zone =~ s/^$tree_root\/*//o;
    $zone = join ('.', reverse (split ('/', $zone)));

    opendir (DIR, $current);
    @files = readdir (DIR);
    closedir (DIR);

    FILE_LOOP: foreach $file (@files) {

	next if $file eq 'RCS';
	next if $file =~ m/^\.\.?$/;

	if (-d "$current/$file") {

	    push (@dirs, "$current/$file");

	} elsif ("$file" eq '.secondary') {

	    $zone = &path_to_zone ($current);
	    $delegated = 0;

	    for ($soa = $current; $soa ne $tree_root; $soa =~ s/\/[^\/]+$//) {

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

		    $delegated = 1;
		    last;

		}

	    }

	    if ($delegated) {

		# print "$zone: Delegated\n";
		$parent_primary = 0;
		
		if (-e "$current/.primary") {

		    $host = '@';

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

		    if ($#recs >= 0) {

			next FILE_LOOP;

		    }

		}

		if (-e "$current/../.primary") {

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

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

		    if ($#recs >= 0) {

			print "\nWARNING: NS record for $host.$zone should be moved to:\n\t$current/.primary\n" if $opt_warn;
			system "$new_primary --zone=$host.$zone --nosoa --f\n" if $opt_fix;

		    } else {

			print "\nERROR: Bad Delegation.  No NS record for $host.$zone\n";

		    }

		    next FILE_LOOP;

		}

		print "\nERROR: Bad Delegation.  No data file to hold NS Record for $zone\n";
		    
	    }

	}
	    
    }

}

exit;
