#!/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->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 $res (@{$conn->get("/cluster/status", {})}) {
    if ($res->{'type'} eq 'cluster') {
        if ($res->{'quorate'} != 1) {
            $np->add_message(CRITICAL, "Cluster is not in quorum");
        } else {
            $np->add_message(OK, "Cluster is in quorum");
        }
    } elsif ($res->{'type'} eq 'node') {
        if ($res->{'online'} == 0) {
            $np->add_message(CRITICAL, "Node $res->{'name'} is offline")
        } else {
            $np->add_message(OK, "Node $res->{'name'} is online")
        }
    }
}

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