#!/usr/bin/perl

use strict;

##print `cat /etc/named.conf`;
$ARGV[0]=~ s/[\r]//sg;
my @domains = split(/[,\n]/,$ARGV[0]);
my $named = "";
`cp /etc/named.conf /etc/named.conf.dnsmeapi`;
open(my $fh,"+<","/etc/named.conf") or die "Could not open /etc/named.conf. REason:" . $!;
flock($fh,2);



my @lines =<$fh>;
my %texts=();
foreach(@domains){
	next if /^\s*$/;
	#print "\nMatching $_";
	my $rs =&check_replace(\@lines,$_);
	if($rs){
		$texts{$_}=&get_domain_zone($_);
		#print "...Replaced with $texts{$_}";
	}
}
#my $c = join("\n",@lines);
my $c = join("",@lines);
my @keys = keys %texts;
if(@keys > 0 ){
	###$c=~ s/^\};\s*$//sg;
	
	foreach(sort @keys){
			$c.=$texts{$_} ."\n";
	}
	##$c.="\n};\n";
}
$c.= "\n";
seek($fh,0,0);
print $fh $c;
truncate $fh, tell($fh);
close($fh);

#zone "g2.cgito.net" {
#        type master;
#        file "g2.cgito.net";
#        allow-transfer {
#                10.0.0.15;
#                common-allow-transfer;
#        };
#};

sub check_replace{
	my($n,$d)=@_;
	my($start,$end,$i)=(0,0,0);
	my($oc,$ec)=(0,0);
	foreach my $line(@$n){
		#chomp $line;
		
		if($line=~ /^\s*zone\s+"\Q$d\E"\s+\{/s){
			#print "\n$line vs $d";	
			$start=$i;
			$oc++;
			##next;
		}elsif($start > 0 && $line=~ /\{/s){
			$oc++ ;
			#print "\n$line vs $oc";	
		}
		if($start > 0 && $line=~ /\};\s*$/s ){
			$ec++;
			#print "\n$line vs $ec";	
			if($ec >=$oc){
			
				$end=$i;
				last;
			}
		}
		$i++;
	}
	print "\n";
	if($start > 0 && $end > $start){
		#print "\nfound: $start vs $end";
		splice(@$n,$start,$end-$start+1);
		#print "\nStart:$start vs $end";
		#print "\nCounted:$oc vs $ec";
		##return "";
		return "1";
	}
	return "";
}
sub get_domain_zone{
	my($d)=@_;
	return qq|zone "$d" {
	type master;
	allow-transfer {208.94.147.135; 208.94.150.198; 63.219.151.12; };
	also-notify {208.94.147.135; 208.94.150.198; 63.219.151.12; };
	file "$d";
};
|
}


