#!/usr/bin/perl -T
# $AFresh1: check_bioctl,v 1.20 2014/06/27 18:59:56 andrew Exp $
########################################################################
# check_bioctl *** A nagios check for OpenBSD bioctl
#
# 2006.07.26 #*#*# andrew fresh <andrew@afresh1.com>
########################################################################
use strict;
use warnings;
use 5.010;

local %ENV = ();

my $NAGIOS_OUTPUT = 1;

my $License = <<'EOL';
Copyright (c) 2009 Andrew Fresh <andrew@afresh1.com>
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
EOL

my $PROGNAME = 'check_bioctl';
my $BIOCTL   = '/sbin/bioctl';
my $SUDO     = '/usr/bin/sudo';

use POSIX;
my $PREFIX;

BEGIN {
    ## no critic 'warnings'
    no warnings 'uninitialized';
    $PREFIX = "/usr/local" || '/usr/local';    # Magic for OpenBSD ports tree
}
use lib $PREFIX . '/libexec/nagios';
use utils qw($TIMEOUT %ERRORS &support);

$SIG{'ALRM'} = sub {
    say "ERROR: $PROGNAME timeout";
    exit $ERRORS{'UNKNOWN'};
};
alarm($TIMEOUT);

use Getopt::Long;
Getopt::Long::Configure('bundling');

# This maps the status we get from bioctl to something nagios can use
my %Status_Map = (
    Online      => 'OK',
    Offline     => 'CRITICAL',
    Degraded    => 'CRITICAL',
    Failed      => 'CRITICAL',
    Building    => 'WARNING',
    Rebuild     => 'WARNING',
    'Hot spare' => 'OK',
    Unused      => 'OK',
    Scrubbing   => 'WARNING',
    Invalid     => 'CRITICAL',
);

my @devices;
my $opt_h;
my $opt_V;

#Option checking
my $status = GetOptions(
    "version|V"  => \$opt_V,
    "help|h"     => \$opt_h,
    "device|d=s" => \@devices,
);

if ( $status == 0 ) {
    print_help();
    exit $ERRORS{'OK'};
}

if ($opt_V) {
    print_revision();
    exit $ERRORS{'OK'};
}

if ( $opt_h || !@devices ) {
    print_help();
    exit $ERRORS{'OK'};
}

my %VOLUMES = read_bioctl( \@devices );
my %STATES  = check_status( \%VOLUMES );

my $have_results = 0;
my $state        = 'OK';
foreach my $error ( sort { $ERRORS{$b} <=> $ERRORS{$a} } keys %ERRORS ) {
    if ( exists $STATES{$error} ) {
        $have_results++;
        $state = $error if $ERRORS{$state} < $ERRORS{$error};

        if ($NAGIOS_OUTPUT) {
            print "$error (" . scalar( @{ $STATES{$error} } ) . ")";
            if ( $error ne 'OK' ) {
                print '<br>';
                print map {" - $_<br>"} @{ $STATES{$error} };
            }
        }
        else {
            print "$error (" . scalar( @{ $STATES{$error} } ) . "):\n";
            print map {"    $_\n"} @{ $STATES{$error} };
        }
    }
}
if ( $have_results == 0 ) {
    say 'No results found';
}
exit $ERRORS{$state};

sub read_bioctl {
    my ($devices) = @_;
    my %volumes;

    foreach my $d ( @{$devices} ) {
        open my $bioctl, q{-|}, $SUDO, $BIOCTL, $d
            or die "Couldn't open bioctl: $!\n";
    LINE: while ( my $line = <$bioctl> ) {
            my ( $i, $item ) = parse_bioctl_line($line);
            next LINE if !defined $i;
            $volumes{$d}{$i} = $item;
        }
        ## no critic 'die'
        close $bioctl
            or die $!
            ? "Error closing bioctl pipe: $!\n"
            : "Exit status $? from bioctl \n";
    }

    foreach my $d ( keys %volumes ) {
        foreach my $i ( keys %{ $volumes{$d} } ) {
            my $item = $volumes{$d}{$i};
            if ( $item->{device} =~ /^\d+:\d+/xms ) {
                $item->{'volume'} = $volumes{$d}{ $item->{volume_id} };
            }
        }
    }

    return %volumes;
}

sub parse_bioctl_line {
    ($_) = @_;
    chomp;

    my @o = map { s/^\s+|\s+$//g; $_ } split;
    return if $o[0] eq 'Volume';

    state $vid = '';
    state $controller;

    my $index = "$vid.$o[0]";
    if ( $o[0] !~ /^\d+$/ ) {
        $controller = shift @o;
        $vid        = $o[0];
        $index      = $vid;
    }

    return $index, {
        controller  => $controller,
        volume_id   => $vid,
        id          => shift @o,
        status      => shift @o,
        size        => shift @o,
        device      => shift @o,
        name        => shift @o,
        description => join ' ', @o,
    };
}

sub check_status {
    my ($volumes) = @_;

    my %states;
    foreach my $d ( sort keys %{$volumes} ) {
        foreach my $i ( sort { $a <=> $b } keys %{ $volumes->{$d} } ) {
            my $volume = $volumes->{$d}->{$i};
            my $state = $Status_Map{ $volume->{'status'} } || 'UNKNOWN';

            push @{ $states{$state} },
                sprintf(
                "%5s %-7s %-11s %s",
                $volume->{'controller'}, $volume->{'device'},
                $volume->{'status'},     $volume->{'name'}
                );
        }
    }
    return %states;
}

sub print_help {
    print <<"EOL";
$PROGNAME plugin for Nagios monitors bioctl on OpenBSD
    $PROGNAME -d <device> [ -d <device2> [ -d ... ] ]

Usage:
    -d, --device=DEVICE
        DEVICE to check.  Can be any device that bioctl(8) accepts
    -h (--help)       usage help
	-V (--version)    version information

EOL

    print_revision();

    print $License;

    return 1;
}

sub print_revision {
    my $rev = '$Revision: 1.20 $';
    $rev =~ s/^\D+([\d\.]+)\D+$/v$1/xms;

    say "$PROGNAME $rev";

    return 1;
}
