#!/usr/bin/perl
# apt-get install libnumber-bytes-human-perl attr
use strict;
use warnings;
use Number::Bytes::Human qw'format_bytes parse_bytes'; 

my %ERRORS = (
    OK       => 0,
    WARNING  => 1,
    CRITICAL => 2,
    UNKNOWN  => 3,
);


showUsage() if (@ARGV and $ARGV[0] eq '--help');


my ($volume, $warn, $crit) = @ARGV;
showUsage() if not defined $volume;
$warn ||= 90; $warn = parse_bytes($warn);
$crit ||= 95; $crit = parse_bytes($crit);


my $cephfs_mount_point = "/mnt/BITED-153874-cephfs_data/";
my $volume_path;
if ($volume =~ /$cephfs_mount_point/) {
    $volume_path = $volume;
} else {
    $volume_path = $cephfs_mount_point . $volume;
}
die "$volume_path is not a directory" if not -d $volume_path;


my $bytes_used  = `getfattr --absolute-names --only-values --name ceph.dir.rbytes $volume_path 2>/dev/null`;
my $bytes_quota = `getfattr --absolute-names --only-values --name ceph.quota.max_bytes $volume_path 2>/dev/null`;

errExit("OK", "CephFS $volume no quota set!\n") if not $bytes_quota;

my $bytes_free            = $bytes_quota - $bytes_used;
my $bytes_free_human      = format_bytes $bytes_free;
my $bytes_used_perc       = $bytes_used * 100 / $bytes_quota;
my $bytes_used_perc_human = int($bytes_used_perc);
my $bytes_total_human     = format_bytes ($bytes_used+$bytes_free);
my $message               = "CephFS $volume ${bytes_total_human}: ${bytes_used_perc_human}% used - $bytes_free_human free\n";

errExit("CRITICAL", $message) if (($warn > 100) and ($crit > 100) and ($bytes_free < $crit));
errExit("WARNING", $message)  if (($warn > 100) and ($crit > 100) and ($bytes_free < $warn));

errExit("CRITICAL", $message) if (($crit < 100) and ($bytes_used_perc >= $crit));
errExit("WARNING", $message)  if (($warn < 100) and ($bytes_used_perc >= $warn));

errExit("OK", $message);

#
#

sub errExit {
    my ($state, $msg) = @_;
    print "$state: $msg";
    exit $ERRORS{$state};
}

sub showUsage {
    print "USAGE:\n$0 <volume> [warn] [crit]\n\nExample:\n$0 MEDA1/156060 90 95\n";
    print "\n";
    print "If warn/crit values > 100, this script assumes it's an absolute 'bytes'\n";
    print "value in stead of treating it as percentages.\n";
    exit 0;
}
