#!/usr/bin/perl

use Getopt::Long;

my @SERVERS;
my @SERVERNAMES;
my @results;
my ($LOOKUP, $RESULT1, $RESULT2, $helpme);

sub help {
	print "Usage: $0 --server <DNS server 1> [--server <...>] --servername <DNS servername 1> [--servername <...>] --lookup <name to lookup> --result <expected result 1> --result <expected result 2>\n";

	exit (3);
}

help if @ARGV == 0;

GetOptions (
	"server=s" => \@SERVERS,
	"servername=s" => \@SERVERNAMES,
	"lookup=s" => \$LOOKUP,
	"result=s" => \@results,
	"help" => \$helpme
) or help;

help if $helpme || @ARGV;

($RESULT1, $RESULT2) = ($results[0], $results[1]);

$DIG = "/usr/bin/dig";
$nservers = 0;

$blankerr = 0;
foreach $srv (@SERVERS) {
	$result[$nservers] = &lookup($LOOKUP, $srv);
	$blankerr = 1 if $result[$nservers] eq '';
	$nservers++;
}

if ($blankerr != 0) {
	print "CRITICAL: some UDNS servers not responding:";
	for ($i = 0; $i < $nservers; $i++) {
		print "  $SERVERNAMES[$i]: ";
		if ($result[$i] eq '') {
			print "no response";
		} else {
			print $result[$i];
			print "*" if (($result[$i] ne $RESULT1) and ($result[$i] ne $RESULT2));
		}
	}

	print "\n";
	exit 2;
}

$differr = 0;
for ($i = 1; $i < $nservers; $i++) {
	$differr = 1 if ($result[0] ne $result[$i]);
}

if ($differr != 0) {
	print "CRITICAL: DNS servers return different results:";
	for ($i = 0; $i < $nservers; $i++) {
		print " $SERVERNAMES[$i] --> $result[$i]";
		print "*" if (($result[$i] ne $RESULT1) and ($result[$i] ne $RESULT2));
	}

	print "\n";
	exit 2;
}

if (($result[0] ne $RESULT1) and ($result[0] ne $RESULT2)) {
	print "CRITICAL: UDNS servers returning incorrect IP address: $result[0]\n";
	exit 2;
}

print "OK: all UDNS servers returning $result[0]\n";
exit 0;


sub
lookup
{
	my ($name, $srv) = @_;

	$res = `$DIG \@$srv $name +short 2>/dev/null`;
	chop $res;
	if ($res =~ /^\d+\.\d+\.\d+\.\d+$/) {
		return $res;
	} else {
		return '';
	}
}

