#!/usr/bin/perl

use strict;
use warnings;

use FindBin;
use lib "$FindBin::Bin/../../lib";
use Wigo::Probe qw/:all/;

###
# DEFAULT CONFIG
###

my $conf = {
    'warnLevel'             => 80,
    'critLevel'             => 95,
    'excludedPartitions'    => ['rootfs','tmpfs','cgmfs','devtmpfs','udev','none'],
};

init( config => $conf );

my $partitionFound = 0;

my @df = `df -hlP`;
if($? != 0)
{
    status  500;
    message "Error when executing df command: ".$!;
    output 1;
}

shift @df;
my $max = 0;
PARTITION: foreach my $line ( @df )
{
    my @splits = split( /\s+/, $line );
 
    my $partition   = $splits[0];
    my $size        = $splits[1];
    my $occupation  = $splits[2];
    my $free        = $splits[3];
    my $usage       = $splits[4];
    my $mountPoint  = $splits[5];
    my $usageRaw    = $1 if ( $usage =~ /(\d+)/ ); 

    foreach my $excludedPartition (@{ config->{'excludedPartitions'} })
    {
        if($partition =~ /^$excludedPartition$/)
        {
            next PARTITION;
        }
    }

    if (exists detail->{$partition})
    {
        # some fs types can be mounted at several places (btrfs)
        # in that case, the first mountpoint reported by df will
        # often be the "main" one, hence don't overwrite it with
        # the potential next ones (only the mountpoint is different).
        next;
    }

    $partitionFound++;

    detail->{$partition} = {
        Size        => $size,
        Used        => $occupation,
        Free        => $free,
        Percentage  => $usage,
        MountPoint  => $mountPoint,
    };

    add_metric { "Tags" => { "Partition" => $partition, "MountPoint" => $mountPoint }, "Value" => $usageRaw };

    # default global values
    my $critLevel = config->{'critLevel'};
    my $warnLevel = config->{'warnLevel'};

    # maybe we have an override for the partition name or the mountpoint ?
    my $override = config->{'levelOverrides'}->{$partition} || config->{'levelOverrides'}->{$mountPoint};
    if ( defined $override )
    {
        $warnLevel = $override->{'warnLevel'} if defined $override->{'warnLevel'};
        $critLevel = $override->{'critLevel'} if defined $override->{'critLevel'};
    }

    if ( $usageRaw > $critLevel )
    {
        raise 300;
    }
    elsif ( $usageRaw > $warnLevel )
    {
        raise 250;
    }

    if ( $usageRaw > $max )
    {
        $max = $usageRaw;
        message "Highest occupation percentage is $usage in partition $partition mounted on $mountPoint ($free free)";
    }
}

if ( !$partitionFound )
{
    status  100;
    message 'No partition have been found.';
}

output 0;
