#!/usr/local/perl/bin/perl -w
BEGIN{
  push @INC, "/usr/lib/perl5/site_perl/5.8.0/i586-linux-thread-multi"
}
use strict;
use Net::DNS;
use Getopt::Long;
use Pod::Usage;
use Time::HiRes qw( usleep ualarm gettimeofday tv_interval );


=head1 NAME

check_dns.pl - DNS-Query and Statistics

=head1 SYNOPSIS

	check_dns.pl -H host -s server -w wlevel -c clevel [-t timeout]
	
	host:    The host to be resolved
	server:  The DNS-server to ask
	timeout: Timeout in seconds
	wlevel:  Warning treshhold (milliseconds)
	clevel:  Critical treshhold (milliseconds)

=head1 DESCRIPTION
                                                                                
This asks a server to resolve a host. It returns OK if the process was
successfull and took less than wlevel milliseconds.

It returns a warning if it took less than clevel milliseconds.

Everything else returns critical. (Also, if it takes longer than timeout.)

=head1 PROBLEMS

This contains a hardcoded perl lib directory. Might wanna change this if
running on a machine with only one perl distribution.

Not too reliable timing functions, I suppose.

=head1 AUTHOR

Copyright (c) 2003 Hannes Schulz <mail@hannes-schulz.de>

=cut

my ($host,$server,$timeout,$wlevel,$clevel);

GetOptions(
	"H=s" => \$host,
	"s=s" => \$server,
	"t=i" => \$timeout,
	"w=i" => \$wlevel,
	"c=i" => \$clevel
);

if(!$timeout){$timeout=10};
alarm($timeout);
$SIG{ALRM} = sub {print "$0 timed out.\n"; exit 2;};

# Do some command line options checking
if(!$server || !$host || !$wlevel || !$clevel){
	pod2usage("$0: Not enough arguments.\nCopyright (c) 2003 Hannes Schulz");
	exit 3;  # Nagios: unknown
}
if($wlevel>=$clevel){
	pod2usage("$0: wlevel is greater clevel!\nCopyright (c) 2003 Hannes Schulz");
	exit 3;  # Nagios: unknown
}

# Initialize the DNS Resolver
my $res = Net::DNS::Resolver->new(
		nameservers => [$server],
		recurse     => 0,
		debug       => 1,
		);

# Start and End time
my ($t0, $t1);

# Get Start Time
$t0 = [gettimeofday];

# Perform the lookup
my $answer = $res->send($host);

# Get End Time
$t1 = [gettimeofday];

# Calculate time elapsed
my $elapsed = int (1000 * tv_interval ( $t0, $t1));

# Generate answer
my $wasok = ($answer->{header}->{rcode} eq "NOERROR");
my $out = $answer->{header}->{rcode}
   . " (took $elapsed ms) | DurationMS=". $elapsed."\n";

# Output for Nagios
print $out;

# Exit for Nagios
exit 2 if(!$wasok);            # Nagios: Critical
exit 2 if($elapsed>$clevel);   # Nagios: Critical
exit 1 if($elapsed>$wlevel);   # Nagios: Warning
exit 0;                        # Nagios: OK
