#!/usr/bin/perl -w
# -*- perl -*-

=head1 NAME

dar_mumusage - Munin plugin to monitor darwin physical memory usage.

=head1 APPLICABLE SYSTEMS

Should work on any darwin (Mac OS X) system with the 'top' command.

=head1 CONFIGURATION

None needed

=head1 INTERPRETATION

The plugin runs the top command and shows the physical memory for the machine.

=head1 BUGS

The stats are a snapshot at the time of the command - a 5 minute average would
be better.

=head1 MAGIC MARKERS

  #%# family=auto
  #%# capabilities=autoconf

=head1 VERSION

  v.0.0.1

=head1 AUTHOR

Copyright (C) 2010.

Original version by J.T.Sage (at) gmail (dot) com.

=head1 LICENSE

GPLv2

=cut

use Munin::Plugin;

if ( defined($ARGV[0])) {
    if ($ARGV[0] eq 'autoconf') {
	$uname = `uname`;
	if ( not ( $uname =~ /Darwin/ ) ) { print "no (not a Darwin System)\n"; }
	else {
		if ( not -x "/usr/bin/top" ) { print "no (top not found)\n"; }
		else {
			print "yes\n";
		}
	}
	exit 0;
    }

    if ( $ARGV[0] eq "config" ) {
	$maxmemcmd = `hostinfo | grep memory`;
	$maxmemcmd =~ m/^.+?: (\d+\.\d+) (\w).+$/;
	$memline = $1;
	if ( $2 eq "m" ) { $memline = $memline * 1024 * 1024; }
	if ( $2 eq "g" ) { $memline = $memline * 1024 * 1024 * 1024; }

	print "graph_title Memory usage\n";
	print "graph_args --base 1024 --lower-limit 0 --upper-limit ".$memline." --rigid\n";
	print "graph_vlabel Bytes\n";
	print "graph_scale yes\n";
	print "graph_category system\n";
	print "wired.label wired\nwired.type GAUGE\nwired.draw AREA\n";
	print "active.label active\nactive.type GAUGE\nactive.draw STACK\n";
	print "inactive.label inactive\ninactive.type GAUGE\ninactive.draw STACK\n";
	print "free.label free\nfree.type GAUGE\nfree.draw STACK\n";
	print "used.label used\nused.type GAUGE\nused.draw LINE2\n";
	exit 0;
    }
}

@top = `top -l1 -n0 -u`;
$quit = 0;
for ( $i = 1;  ($i < $#top and $quit == 0); $i++ ) {
	if ( $top[$i] =~ /^PhysMem/ ) {
		$wired = $active = $inactive = $free = $used = $top[$i];
		$wired =~ s/^.+?: (\d+)M wired.+$/$1/; chomp $wired; $wired = $wired * 1024 * 1024;
		$active =~ s/^.+?, (\d+)M active.+$/$1/; chomp $active; $active = $active * 1024 * 1024;
		$inactive =~ s/^.+?, (\d+)M inactive.+$/$1/; chomp $inactive; $inactive = $inactive * 1024 * 1024;
		$free =~ s/^.+?, (\d+)([M|K]) free.+$/$1/; chomp $free; $free = $free * 1024 * 1024; if ( $2 eq "K" ) { $free = $free / 1024; }
		$used =~ s/^.+?, (\d+)([M|G]) used.+$/$1/; chomp $used; $used = $used * 1024 * 1024; if ( $2 eq "G" ) { $used = $used * 1024; }
		print "wired.value " . $wired . "\n";
		print "active.value " . $active . "\n";
		print "inactive.value " . $inactive . "\n";
		print "free.value " . $free . "\n";
		print "used.value " . $used . "\n";
		$quit = 1;
	}
}




# vim:syntax=perl
