#!/usr/bin/perl
# 
# apt-get install libjson-perl

use strict;
use warnings;
use JSON qw'decode_json';

# Scheelt een ton aan dependencies op nagios-plugins
#use lib "/usr/lib/nagios/plugins";
#use utils qw(%ERRORS);
my %ERRORS = (
    OK       => 0,
    WARNING  => 1,
    CRITICAL => 2,
    UNKNOWN  => 3,
);

if (@ARGV and $ARGV[0] eq '--help') {
    print "$0\n\nJust run it\n";
    exit;
}

# Whitelist, skip deze client entries
my %whitelist = map {$_ => 1 } (
    'client.BITED-156140-cephfs', # Monitoring mag alles lezen
);

my $json = `ceph auth list --format=json`;
my $data = decode_json $json;

# Basic sanity check
if (not $json or not $data or $json !~ /client.admin/) {
    print "UNKNOWN: NO DATA\n";
    exit $ERRORS{UNKNOWN};
}

my @error;
my $t=0;
foreach my $item (@{$data->{auth_dump}}) {
    # Skip everything that isn't '^client.BARNY-'
    next unless $item->{entity} =~ /^client\.\w{5}-/;

    # Skip if no mds auth defined
    next unless $item->{caps}->{mds};

    $t++;

    # Skip if whitelisted
    next if $whitelist{ $item->{entity} };

    # MDS caps should match "^allow r|rw path=/BARNY/123456$"
    next if $item->{caps}->{mds} =~ m#^allow (r|rw|rwp) path=/\w{5}/\d{6}$#;

    # Ok something's wrong
    push @error, sprintf("%s MDS %s", $item->{entity}, $item->{caps}->{mds});
}

if (@error) {
    print "CRITICAL: ceph MDS auth: ".join(" ", @error)."\n";
    exit $ERRORS{'CRITICAL'};
}
else {
    print "OK: $t MDS clients ok\n";
    exit $ERRORS{'OK'};
}
