#!/usr/bin/perl

# Author: tomekk
# e-mail:  tomekk/@/tomekk/./org
# home page: http://tomekk.org/
#
# Version 0.2
#
# This file is Copyrighted under the GNU Public License.
# http://www.gnu.org/copyleft/gpl.html
##########################################################

# fixed: string comparison ( fail ;o) )

# some uses
use strict;
use File::Copy;
use Digest::MD5;
use LWP::Simple;

# named conf
my $named_conf = "/etc/bind/slaves.conf";

# remote file with zones
my $remote_file = "bindzones.txt";

# http host/address without 'http://'
my $remote_host = "10.10.10.10";

# temp dir for 'zones' files (.tmp etc)
my $temp_dir = "/etc/bind";

##########################################################
# check if the input mark is specified or not
if (!$ARGV[0])
{
        print "no input mark specified, exiting";
        exit 1;
}

# farm of vars
my ($zones_file, $temp_zones_file);
my (@zones_lines, $zones_line);
my ($domain_ip, $mark, $domain_name, $master_ip);

# some aliases
$zones_file =  $temp_dir . "/" . $remote_file;
$temp_zones_file = $temp_dir . "/" . $remote_file . ".tmp";

# get remote file
getstore("http://" . $remote_host . "/" . $remote_file, $temp_zones_file) or die 'unable to get remote file';

# check if exists, compare files (md5sum)
if (-e $zones_file)
{
	if (md5sum($zones_file) eq md5sum($temp_zones_file))
	{
		print "$zones_file and $temp_zones_file are the same, exiting";
		exit 0;
	}
}

# copy 'tmp' to 'file'
copy($temp_zones_file, $zones_file) or die "copy failed: $!";

# read zones file into array
open(ZONES, $zones_file) or die "cannot open zones file: $zones_file";
@zones_lines = <ZONES>;
close(ZONES);

# open 'named conf'
open(NAMED_CONF,">" . $named_conf);

# parse zones file
foreach $zones_line (@zones_lines)
{
        $zones_line = trim($zones_line);

        ($domain_ip, $mark) = split(':', $zones_line);
	
	if ($mark =~ m/$ARGV[0]/)
	{
		($domain_name, $master_ip) = split(',', $domain_ip);

		print NAMED_CONF "zone \"$domain_name\" IN {\n";
		print NAMED_CONF "\ttype slave;\n";
		print NAMED_CONF "\tfile \"$domain_name\";\n";
		print NAMED_CONF "\tmasters { $master_ip; };\n";
		print NAMED_CONF "\tallow-notify { $master_ip; };\n";
		print NAMED_CONF "};\n\n";
		
	}
}

# close it
close(NAMED_CONF);

# reload named
system("killall -HUP named >/dev/null 2>&1");

# perl md5sum of file ;(
sub md5sum
{
	my $file = shift;
	open(FILE, $file) or die "cannot open file $file";
	binmode(FILE);
	my $sum = Digest::MD5->new;
	$sum->addfile(*FILE);
	my $digest = $sum->hexdigest;
	close(FILE);

	return $digest;
}

# c'mon PERL, trim!
sub trim
{
        my $trim = shift;
        $trim =~ s/^\s+//;
        $trim =~ s/\s+$//;
        return $trim;
}

