#!/usr/bin/perl

# $Id: axfr2data.pl,v 1.1 2004/11/21 10:50:54 hutch Exp $
# purpose of the script:
# pull dns zone info from a primary server $host
# the receiving ip must have permission to do so, set in
# /etc/named.conf on the primary server
my $Verbose = 1;

# the primary server from where the zones are being fetched
my $host = "xx.xx.xx.xx";

my $indir = "./";
# the list of domains to fetch
my $list = "$indir/domains.txt";
if (! -f "$list") {
	die "$list not found\n";
}
# where the output will be stored
my $outdir = "./tmp";
my $donelist = "$outdir/DONELIST.txt";

# output files suffix
my $suffix = ".data";
my $dnstools = "/usr/local/bin";
my ($command, @Domains, $l, $file, $output, @Err, @Done, @in, %saw, $ret);

##############################
# get $list, put into @Domains
# skips commented out lines
open (MYFILE, "$list") or die("$!");
while($l=<MYFILE>) {
	chomp($l);
	$l =~ s/^\s+|\s$//g;
	if($l =~ /^#/) { next; }
	push(@in, $l) if($l);
}
close(MYFILE);
print "got $list\n"    if($Verbose);

# unique
@Domains = grep(!$saw{$_}++, @in);

$domtot = $#Domains + 1;
# get the axfr data
foreach $l (@Domains) {
	next if(! $l);
	$file = "$outdir/" . $l . "$suffix";
	$command = "$dnstools/tcpclient $host 53 $dnstools/axfr-get $l $file $file.tmp";
	print "running command $command: "    if($Verbose);
	system("$command");
	#$output = `$command`;
	$ret = $?;
	if ($output or $ret) {
		# could be an error
		print ($output ? "output for $l: $output\n" : '') .
			($ret ? "return for $l: $ret\n" : '');
		push(@Err, $l);
		print "error\n"    if($Verbose);
	}
	else {
		push(@Done, $l);
		print "done\n"    if($Verbose);
	}
}

$errtot = $#Err + 1;
if ($errtot) {
	print "There may have been $errtot errors in the following domains:\n";
	foreach (@Err) {
		print $_ . "\n";
	}
}

$donetot = $#Done + 1;
if (! $donetot) {
	die "nothing to do!\n";
}

open(MYFILE, ">$donelist") or die("$!");
foreach (@Done) {
	print MYFILE $_ . "\n";
}
close(MYFILE);

print "$donetot of $domtot zones transferred\n"    if($Verbose);
## eof ##

