#!/usr/bin/perl -w
####
#       Author:         Zhivko Todorov <ztodorov@neterra.net>
#       Date:           07-Jan-2015
#       Version:        0.0.3
#       License:        GPL
####

use strict;
use warnings;
use Getopt::Long;

# Nagios parsable return codes
use constant OK       => 0;
use constant CRITICAL => 2;
use constant UNKNOWN  => 3;

MAIN:
{
        # Values for variable below will be collected from CLI
        my $nrpe_path     = undef(); # Path to nrpe plugin
        my $ip1           = undef(); # ip1
        my $ip2           = undef(); # ip2
        my $help          = undef(); # Ask for usage info.


        # Receive command line parameters.
        GetOptions
        (
                "nrpe_path=s"    => \$nrpe_path,
                "ip1=s"          => \$ip1,
                "ip2=s"          => \$ip2,
                "help"           => \$help
        );

        # Show usage info.
        if($help)
        {
                showHelp();
                exit(OK);
        }

        # Parse command line arguments.
        if(!parseCLIArgs($nrpe_path, $ip1, $ip2))
        {
                print "Invalid command line arguments supplied.";
                showHelp();
                exit(UNKNOWN);
        }


        my $ip1status=getNRPEstatus($nrpe_path, $ip1);
        my $ip2status=getNRPEstatus($nrpe_path, $ip2);

        if($ip1status eq $ip2status)
        {
                print "Status: CRITICAL - $ip1 $ip1status; $ip2 $ip2status\n";
                exit(CRITICAL);
        }

        print "Status: OK - $ip1 $ip1status; $ip2 $ip2status\n";
        exit(OK);


} # END MAIN

sub getNRPEstatus
{
        my ($nrpe_path, $ip) = @_;
        my @ip_raw = (); # Raw nrpe output

        @ip_raw = `$nrpe_path -H $ip -c check_ipvs_status`;

        chomp(@ip_raw);

        return "MASTER"
                if(grep(/MASTER/, @ip_raw));

        return "BACKUP"
                if(grep(/BACKUP/, @ip_raw));

        print "Status: Unknown\n";
        exit(UNKNOWN);
} # END getNRPEstatus

sub parseCLIArgs
{
        my ($nrpe_path, $ip1, $ip2) = @_;

        return 0
                if(!$nrpe_path or !-x $nrpe_path);

        # Check for syntatically valid IP address
        return 0
                if($ip1 !~ /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/);

        return 0
                if($ip2 !~ /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/);

        return 1;
} # END sub parseCLIArgs



sub showHelp
{
        my @showHelpMsg =
        (
                "USAGE:",
                "    -n --nrpe_path  /path/to/check_nrpe.",
                "    -ip1 --ipaddress1    IP address of host 1.",
                "    -ip2 --ipaddress2    IP address of host 2.",
                "    -h --help  Display help message (this).",
                "",
        );

        print join("\n", @showHelpMsg);
} # END sub showHelp