#!/usr/bin/perl
use Getopt::Long;
use strict;

our ($opt_dir, $opt_max, $opt_warn, $opt_crit, $opt_g, $opt_k);
our ($du_cmd) = "/usr/bin/du";

sub parse_args {
	GetOptions(
                "d=s" => \$opt_dir,"directory=s" => \$opt_dir,
                "s=f" => \$opt_max,"max=f" => \$opt_max,
                "w=f" => \$opt_warn,"warning=f" => \$opt_warn,
                "c=f" => \$opt_crit,"critical=f" => \$opt_crit,
		"g"   => \$opt_g,
		"k"   => \$opt_k,
                );

	usage() if (!defined($opt_dir) || !defined($opt_max) || !defined($opt_crit) || !defined($opt_warn) );
	$opt_max *= 1024 if ($opt_g);
	$opt_max /= 1024 if ($opt_k);

}

sub usage {
	print "Usage:\n";
	print "\t$0 -d <directory || file> -s <max size in mbytes>  -w <warning percent> -c <critical percent> [-g] [-k]\n";
	print "\tYou can use -g to specify a max size in gbytes or -k to kbytes\n";
	exit(3);
}


sub main {

	parse_args();

	my $ret = `$du_cmd -Dshm $opt_dir`;
	#print "---$ret----\n";

	$ret =~ m/^([\d.]+)\D*\s+.*$/;
	my $used = $1;
	my $perc_used = sprintf( "%.3f", ($used * 100)/$opt_max );

	if ($perc_used > $opt_crit) {
		print "CRITICAL - Utilizacao de $opt_dir em $perc_used\% (max $opt_max mb) |used=$perc_used\%;$opt_warn;$opt_crit;;\n";
		exit(2);
	}
	if ($perc_used > $opt_warn) {
                print "WARNING - Utilizacao de $opt_dir em $perc_used\% (max $opt_max mb) |used=$perc_used\%;$opt_warn;$opt_crit;;\n";
                exit(1);
        }

	print "OK - Utilizacao de $opt_dir em $perc_used\% (max $opt_max mb) |used=$perc_used\%;$opt_warn;$opt_crit;;\n";
	exit(0);

}

main();
