#!/usr/bin/perl

use strict;
use warnings;
use PVE::APIClient::LWP;
use Monitoring::Plugin;
use PVE::AccessControl;
use PVE::INotify;
use JSON;


# Create the Monitoring::Plugin object
my $np = Monitoring::Plugin->new(
    version => '1.0',
    usage => "Usage: %s [ -v|--verbose ] [-t <timeout>] "
        . "[ -c|--critical=<threshold> ] [ -w|--warning=<threshold> ]",
);

$np->add_arg(
    spec => 'warning|w=s',
    required => 1,
    help => '-w, --warning=INTEGER .  Percentage free when status is WARNING ');

$np->add_arg(
    spec => 'critical|c=s',
    required => 1,
    help => '-c, --critical=INTEGER .  Percentage free when status is CRITICAL ');

$np->getopts;

my $hostname = PVE::INotify::read_file("hostname");

my $ticket = PVE::AccessControl::assemble_ticket('root@pam');
my $csrftoken = PVE::AccessControl::assemble_csrf_prevention_token('root@pam');

my $conn = PVE::APIClient::LWP->new(
    ticket => $ticket,
    csrftoken => $csrftoken,
);

foreach my $storage (@{$conn->get("/storage", {})}) {
    if (defined($storage->{'disable'})) {
        # Ignore disabled storages
        next;
    }

    if (defined($storage->{'nodes'})) {
        # If we have a node-limitation, check if we are in the list of
        # allowed nodes
        if ( !grep( /^$hostname$/, split(',', $storage->{'nodes'}))) {
            # We are not allowed here
            next;
        }
    }

    my $res = $conn->get("/nodes/$hostname/storage/$storage->{'storage'}/status", {});
    if ($res->{'active'} > 0) {
        my $pct = sprintf("%.2f",$res->{'used'}/($res->{'total'}/100));
        my $code = $np->check_threshold(
            check => $pct,
            warning => 100-$np->opts->warning,
            critical => 100-$np->opts->critical);
        $np->add_message($code, "$pct% in use on $storage->{'storage'}");
    } else {
        $np->add_message(CRITICAL, "$storage->{'storage'} is offline");
    }
}

my ($code, $message) = $np->check_messages();
$np->plugin_exit($code, $message);
