#!/usr/bin/perl

use strict;
use warnings;
use Martnet::DDNS;

my $ddns = Martnet::DDNS->new();

my $cfgpath = '/etc/bind';
my $datapath = '/var/lib/bind';

my %files = ( 'unified.zones.9' => '*' );

our %fixes = ( '_custom' => 'add-custom',
	       '_vhosts' => 'add-vhost',
	       '_pureslave' => 'add-slave',
	       '*' => 'one of the add-* scripts',
    );

foreach my $i (keys %files) {
    validate_file($cfgpath . '/' . $i, $files{$i});
}

exit 0;

sub validate_file {
    my ($path, $expected_type) = @_;

    open(my $fh, $path) || die "Can't open $path: $!";

    while (<$fh>) {
	my ($zonename) = ($_ =~ /zone \"([^\"]+)\"/i);
	next unless ($zonename);
	$zonename = lc($zonename);
	unless ($zonename =~ /\.$/) {
	    $zonename .= '.'; # must end with a dot
	}

	findOrDie($path, $zonename, $expected_type);
    }
    close $fh;
}

sub findOrDie {
    my ($path, $zonename, $expected_type) = @_;
    
    my $type = $ddns->type($zonename);
    unless ($type) {
	my $fix = $fixes{$expected_type};
	die "domain $zonename is not managed, but is in $path [expected $expected_type]; to fix, either remove the domain from the file, or use $fix to fix it";
    }
    if ($expected_type ne '*') {
	unless ($type eq $expected_type) {
	    die "domain $zonename is managed in $path of type [$type] but should be [$expected_type] if it's in that file";
	}
    }
} 
