#!/usr/bin/perl
#

=head1 NAME

quota_usage_ - Plugin to monitor quota on a specified device. 

=head1 APPLICABLE SYSTEMS

Needs repquota and root privs

=head1 USAGE

Create Service Link /etc/munin/plugins/quota-usage_<dev>
for example C<quota-usage_hda3>. Use underscores instead of slashes, for
example to monitor C</dev/mapper/vol-foo>, name this C<quota-usage_mapper_vol-foo>

This plugin uses the soft and hard quota data for warning and critical
levels respectively.

=head1 MAGIC MARKERS

  #%# family=manual

=head1 AUTHOR

Unknown author

Source: L<https://svn.koumbit.net/koumbit/trunk/munin-plugins/quota-usage>

L<http://munin-monitoring.org/attachment/ticket/143/quota-usage>

=head1 LICENSE

GPLv2

=cut

use strict;
use warnings;
use Munin::Plugin;

# We do some magic to allow device strings with underscore to mean a /
# So to monitor /dev/mapper/vol-foo use quota-usage_mapper_vol-foo
my @tmp = split(/_/, $0);
shift @tmp;
my $dev = join("/", @tmp);
my %users;

open (REP, "/usr/sbin/repquota /dev/$dev |") or exit 22;
while (<REP>) {
	chomp;
	if (/^-+$/../^$/) {
		my @data = split(/ +/);

		next if !$data[0] || $data[0] =~ /^#/;

		if ( @data > 2 && $data[2] > 0 ) {
		  $users{$data[0]}[0] = $data[2]; # current usage
		  $users{$data[0]}[1] = $data[3]; # Soft quota
		  $users{$data[0]}[2] = $data[4]; # Hard quota
		}
	}
}
close REP;

my @users_by_usage = sort { $users{$b} <=> $users{$a} } keys(%users);

if ($ARGV[0] and $ARGV[0] eq "config") {
	print "graph_title Filesystem usage by user on $dev\n";
	print "graph_args --base 1024 --lower-limit 0\n";
	print "graph_vlabel bytes\n";
	print "graph_category disk\n";
	for my $user (@users_by_usage) {
		my ($uid, $name) = (getpwnam($user))[2,6];
		my $id = clean_fieldname($user);
		$name = $user if (length($name) < length($user));
		$name = (split(/,/, $name))[0];

		printf "%s.label %s\n", $id, $name;
		printf "%s.cdef %s,1024,*\n", $id, $id;

		if ($users{$user}[1] && $users{$user}[1] > 0) {
		  printf "%s.warning %s\n", $id, $users{$user}[1];
		}
		if ($users{$user}[2] && $users{$user}[2] > 0) {
		  printf "%s.critical %s\n", $id, $users{$user}[2];
		}

		if ($uid < 200) {
		  printf "%s.graph no\n", $id
		}
	}
} else {
	for my $user (@users_by_usage) {
		my $esc = $user;
		$esc = clean_fieldname($esc);
		printf "%s.value %s\n", $esc, $users{$user}[0];
	}
}
