#!/usr/bin/perl -w
#
# grep-like nagios plugin - returns OK if regex is found, else CRITICAL.
#

=todo

+ add an ignore case arg (-i ?)
- add an inversion arg (-v ?)
- add a command arg (-c ?) as an alternative to reading stdin

=cut

use strict;
use Nagios::Plugin::Getopt;
use Nagios::Plugin 0.1301;

my $ng = Nagios::Plugin::Getopt->new(
  usage => qq(Usage: %s [-v] <regex>),
  version => '0.2',
  url => 'http://www.openfusion.com.au/labs/nagios/',
  blurb => qq(This plugin acts like an egrep for nagios, reading from stdin until EOF, 
and returning OK if the given regex is found, and CRITICAL otherwise.),
);
$ng->arg(
  spec => 'ignore-case|i',
  help => q(-i, --ignore-case
   Ignore case distinctions when matching.),
);
$ng->arg(
  spec => 'command|C=s',
  help => q(-C, --command
   Command to execute (and grep output instead of stdin).),
);
$ng->arg(
  spec => 'invert|invert-match',
  help => q(--invert, --invert-match
   Invert sense of match i.e. return CRITICAL if regex is found, OK otherwise.),
);
$ng->getopts;

my $np = Nagios::Plugin->new;

$np->die("no regex argument given to search for") unless @ARGV;
$np->die("too many arguments found - please quote multi-word regex") if @ARGV > 1;

my $regex = shift @ARGV;

alarm($ng->timeout);

my $data = '';
if (my $cmd = $ng->command) {
  $data = qx($cmd);
}
else {
  while (<>) { $data .= $_ }
}

# Check match
my @match = ();
my $ic = $ng->get('ignore-case') ? 'i' : '';
push @match, $1 while $data =~ m/((?$ic).*$regex.*)/mgc;

if (@match) {
  my $match = join(' ', @match);
  $np->nagios_exit($ng->invert ? CRITICAL : OK, $match);
}

else {
  $np->nagios_exit($ng->invert ? OK : CRITICAL, "Regex '$regex' not found.");
}

#arch-tag: 75170fd6-c360-4082-a6f2-b5bcb763b244
#vim:ft=perl:ai:sw=4

