#!/usr/bin/perl -w

# named check module

# Version: $Revision: 0.15 $
# Author: Benjamin Oshrin and Matt Selsky
# Date: $Date: 2004/07/15 16:28:48 $
#
# Copyright (c) 2002 - 2003
# The Trustees of Columbia University in the City of New York
# Academic Information Systems
# 
# License restrictions apply, see doc/license.html for details.

use strict;
use FindBin;
use lib "$FindBin::Bin/../common";
use Survivor::Check;

use Net::DNS;

my %argfmt = ('name' => 'string',
              'type' => 'optional string default(A)',
	      'port' => 'optional number between(1,65535) default(53)');

my $sc = new Survivor::Check();

$sc->GetOpt(\%argfmt, \&NamedValidate);

my $r = $sc->Exec( \&NamedCheck);

exit($r);

sub NamedValidate {
    return(MODEXEC_OK, 0, 'Named OK');
}

sub NamedCheck {
    my $self = shift;
    my $host = shift;

    my $res = new Net::DNS::Resolver;
    $res->nameservers($host);
    $res->port($self->Arg('port'));
    $res->retry( 2 ); # good enough...or entire module may timeout

    my $query = $res->query($self->Arg('name'), $self->Arg('type'));

    if(!defined $query) {
        if( $res->errorstring eq 'NOERROR' ) {
            return(MODEXEC_PROBLEM, 0, 'No '.uc( $self->Arg('type') ).
		   ' records found for '.$self->Arg('name'));
        } else {
            return(MODEXEC_PROBLEM, 0, $res->errorstring);
        }
    } else {
	my $count;

	foreach my $rr ($query->answer) {
	    if( $rr->type eq uc( $self->Arg('type') ) ) {
		$count++;
	    }
	}

	return(MODEXEC_OK, $count, "Found $count " . uc( $self->Arg('type') ) .
	       ' ' . ($count > 1 ? 'records' : 'record') . ' for ' .
	       $self->Arg('name') );
    }
}
