#!/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';

umask 0117;

$SIG{'INT'} = 'bail';

die "$tree_root doesn't exist or is not writable.\n" unless (-e $tree_root && -d _ && -w _);
die "$zoneinfo doesn't exist or is not writable.\n" unless (-e $zoneinfo && -w _);

open (CLASSINFO, $classinfo) || die "Can't open .classinfo: $!\n";

CLASS_READ_LOOP: while (<CLASSINFO>) {

    chomp;
    s/[\;\#].*$//o;		# Kill comments
    s/^\s*//o;			# Kill leading whitespace
    s/\s*$//o;			# Kill trailng whitespace

    next CLASS_READ_LOOP unless $_; # Bail if $_ is NIL

    ($key, $val) = split;
    $val = $default_class unless $val;
    die "Bad entry - line [$.]: $_\n" unless $key;
    $class{lc($key)} = lc($val);

}

close (CLASSINFO);

open (ZONEINFO, $zoneinfo) || die "Can't open .zoneinfo: $!\n";
open (TMP_ZONEINFO, ">$zoneinfo.tmp") || die "Can't open .zoneinfo.tmp: $!\n";

ZONE_READ_LOOP: while (<ZONEINFO>) {

    chomp;
    s/^\s*//o;			# Kill leading whitespace
    split;

    $current_zone = $_[0];
    $numtabs = 4 - int(length($current_zone)/8);
    $ws = $numtabs > 0 ? "\t" x $numtabs : ' ';

    ZONE_COMPARE: for (;;) {

	if (defined ($class{$current_zone})) {

	    print TMP_ZONEINFO "$_[0]$ws$class{$current_zone}\n";
	    last ZONE_COMPARE;

	} else {

	    next ZONE_COMPARE if $current_zone =~ s/^[^.]+\.//o;
	    print TMP_ZONEINFO "$_[0]${ws}$default_class\n";
	    last ZONE_COMPARE;
	    
	}

    }

}

close (ZONEINFO);
close (TMP_ZONEINFO);

system "$sort $zoneinfo.tmp -b -o $zoneinfo +1 -2 +0 -1";
unlink "$zoneinfo.tmp";

exit;

sub bail {

    close (CLASSINFO);
    close (ZONEINFO);
    close (TMP_ZONEINFO);
    exit;

}
