#!/usr/bin/perl
#
# Copyright 2013 SPARTA, Inc.  All rights reserved.
# See the COPYING file distributed with this software for details.
#
# owl-collect-rrsec
#
# Revision History
#	2.0	Released as part of DNSSEC-Tools 2.0.		130506
#	2.0.1	Added header, version, and pod skeleton.	130909
#

#######################################################################
#
# Version information.
#
my $NAME   = "owl-collect-rrsec";
my $VERS   = "$NAME version: 2.0.1";
my $DTVERS = "DNSSEC-Tools version: 2.0";

use strict;
use Data::Dumper;

if ($#ARGV != 2) {
    die "usage: $0 SOURCESENSOR DOMAIN NAMESERVER";
}

my $FILEEXT = 'rrsec';

my ($source, $domain, $nsrvr) = @ARGV;
my $datadir = "/owl/data/$source/data/$FILEEXT";
my $tmpfile = "/tmp/rrsec-collected-$domain.$$";

my $lastdate = 0;
my @files = ();

# find all the most recent relevant files
opendir(DIR, $datadir) || die "$@";
while ($_ = readdir(DIR)) {
    next if (!/rrsec$/);

    my @fields = split(/,/);

    # make sure we have the right sensor
    next if ($fields[1] ne $source);

    # make sure we have the right domain
    next if ($fields[2] ne $domain);

    # make sure we have the right name server
    next if ($fields[3] ne $nsrvr);

    if ($fields[0] > $lastdate) {
	$lastdate = $fields[0];
	@files = ([$_, @fields]);
    } elsif ($fields[0] == $lastdate) {
	push @files, [$_, @fields];
    }
}

#print Dumper(\@files);

# join the last outputs from them into a separate file
open(T,">$tmpfile");
my $text = "";
foreach my $file (@files) {
    open(F, "$datadir/$file->[0]");
    while (<F>) {
	if ($text =~ /<<>> DiG/) {
	    # start of new output
	    $text = "";
	}
	$text .= $_;
    }

    print T $text;
}

# run donuts
# open(DONUTS,"perl -I /usr/local/dnssec-tools-wes/lib/perl5 -I /usr/local/dnssec-tools-wes/lib/perl5/x86_64-linux-thread-multi/ /usr/local/dnssec-tools-wes/bin/donuts -v -i 'DNSSEC_RRSIG_TTL_MATCH_ORGTTL|DNSSEC_RRSIG_TTL_MUST_MATCH_RECORD|DNSSEC_MISSING_NSEC'  -O nagiossummary $tmpfile $domain|");

open(DONUTS,"perl /usr/local/bin/donuts -v -i 'DNSSEC_RRSIG_TTL_MATCH_ORGTTL|DNSSEC_RRSIG_TTL_MUST_MATCH_RECORD|DNSSEC_MISSING_NSEC'  -O nagiossummary $tmpfile $domain|");

# output the single expected line
$_ = <DONUTS>;
print;

# set the exit status
my $exitstatus = 0;
$exitstatus = 2 if ($_ !~ /:0/);

# clean up and exit
close(DONUTS);
unlink($tmpfile);
exit $exitstatus;


1;

###############################################################################

=pod

=head1 NAME

owl-collect-rrsec - Nagios plugin to do something with Owl sensor data

=head1 SYNOPSIS

  owl-collect-rrsec <sourcesensor> <domain> <name server>

=head1 DESCRIPTION

(to be added)

=head1 NAGIOS USE

(to be added)

=head1 OPTIONS

(to be added)

=head1 SEE ALSO

(to be added)

=head1 COPYRIGHT

Copyright 2013 SPARTA, Inc.  All rights reserved.
See the COPYING file included with the DNSSEC-Tools package for details.

=head1 AUTHOR

Wes Hardaker, hardaker@tislabs.com

=cut

