#! /usr/bin/perl
# © 2011 Heiko Schlittermann <hs@schlittermann.de>
# source: https://ssl.schlittermann.de/hg/check-by-nsca

use strict;
use warnings;
use Sys::Hostname;
use File::Basename;
use Getopt::Long;
use Pod::Usage;
use Readonly;

Readonly my $ME => basename $0;

delete @ENV{ grep /^(LC_|LANG)/ => keys %ENV };
$ENV{LC_ALL} = "C";

my %o = (
    hostname  => hostname(),
    svcname   => "-",
    nsca_host => undef,
    nsca_port => undef,
    debug     => undef,
);

MAIN: {
    Getopt::Long::Configure("bundling");
    GetOptions(
        "H|hostname=s"    => \$o{hostname},
        "S|servicename=s" => \$o{svcname},
        "nsca-host=s"     => \$o{nsca_host},
        "p|nsca-port=i"   => \$o{nsca_port},
        "h|help"          => sub { pod2usage(-verbose => 1, -exit => 0) },
        "m|man"           => sub {
            pod2usage(
                -verbose   => 2,
                -exit      => 0,
                -noperldoc => system("perldoc -V 2>/dev/null 1>/dev/null")
            );
        },
        "d|debug" => \$o{debug},
    ) or pod2usage();

    my $cmdline = "send_nsca -H '$o{nsca_host}'"
      . (defined $o{nsca_port} ? " -p $o{nsca_port}" : "");

    $_ = `@ARGV`;
    my $rc = $? >> 8;

    if ($o{svcname} eq "-") {
        /^(?<service>\S+)\s/ or die "$ME: Can't guess servicename!\n";
        $o{svcname} = $+{service};
    }
    $_ =
      join "\t" => $o{hostname},
      length($o{svcname})
      ? $o{svcname}
      : (), $rc, $_;

    if ($o{debug}) {
        print $cmdline, "\n$_\n";
        exit;
    }

    open(SEND, "|$cmdline") or die "$ME: Can't open `$cmdline': $!\n";
    print SEND $_;
    close(SEND)
      or die $!
      ? "$ME: Error closing `$cmdline': $!\n"
      : "$ME: Error status from `$cmdline': $?\n";

}

__END__

=head1 NAME

 submit-via-nsca - submit service, or host check results via nsca

=head1 SYNOPSIS

 submit-via nsca --nsca-host {host} [options] -- {check} [check-options]

=head1 DESCRIPTION

This simple script submits the result of nagios check plugins to an NSCA
receiver. The script does not send the result itself, it's merely a
wrapper around C<send_nsca>.

=head1 OPTIONS

=over

=item B<-H> | B<--hostname> I<hostname>

The hostname to be sent along with the result. (defaults to the local
host name).

=item B<-S> | B<--servicename> I<servicename>

The servicename to be sent along with the result. If a single "-" (dash)
is used, the servicename is guessed from service check output, if ""
(empty), a host check is submitted. (default: "-")

=item B<--nsca-host> I<hostname>

The destination host (the host, where the NSCA listener is running).
(no default).

=item B<--nsca-port> I<port>

The destination port. (default depends on the C<send_nsca> utility)

=item B<-h> | B<--help>

=item B<-m> | B<--man>

The long or short help text.

=back

=head1 AUTHORS

Heiko Schlittermann L<mailto:hs@schlittermann.de>, the source can be
found at L<https://ssl.schlittermann.de/hg/submit-via-nsca>.
