#!/usr/bin/perl -w

use strict;
use POSIX;
use Getopt::Long;
use Win32::DriveInfo;
use Win32API::File qw(
    getLogicalDrives 
    GetVolumeInformation 
    );

my $min_free_warn = 10;
my $min_free_crit = 5;
my @excludes      = ();
my $warning_text  = "";
my $critical_text = "";
my $normal_text   = "";
my $checked_drives= 0;

GetOptions ("w=i"  => \$min_free_warn,
            "c=i"  => \$min_free_crit,
            "x=s@" => \@excludes,
           )
or die("Error in command line arguments\n");

my @drives = getLogicalDrives();
foreach my $drive ( @drives ) {

    my $excluded = 0;
    foreach my $exclude ( @excludes) {
        if ("$exclude\\" eq $drive) {
            $excluded = 1;
        }
    }
    if ($excluded == 1) { 
        next; 
    } else {
        $checked_drives++;
    }

    my ($SectorsPerCluster,
        $BytesPerSector,
        $NumberOfFreeClusters,
        $TotalNumberOfClusters,
        $FreeBytesAvailableToCaller,
        $TotalNumberOfBytes,
        $TotalNumberOfFreeBytes) = Win32::DriveInfo::DriveSpace($drive);
     
    my $FreePercentage = floor (($TotalNumberOfFreeBytes / $TotalNumberOfBytes) * 100);
     
    if ( $FreePercentage < $min_free_crit) {
        $critical_text .= " - Free diskspace for $drive is $FreePercentage% (threshold: $min_free_crit%)";
    } elsif ( $FreePercentage < $min_free_warn) {
        $warning_text .= " - Free diskspace for $drive is $FreePercentage% (threshold: $min_free_warn%)";
    } else {
        $normal_text .= " - $drive $FreePercentage% free";
    }
}

if ($critical_text ne "") {
    print "CRITICAL" . $critical_text . "\n";
    exit 2;
} elsif ($warning_text ne "") {
    print "WARNING" . $warning_text . "\n";
    exit 1;
} elsif ($checked_drives == 0) {
    print "WARNING - All drives to check where excluded or nothing to check\n";
    exit 1;
} else {
    print "OK" . $normal_text . "\n";
    exit 0;
}
