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

=head1 NAME

dar_cpuusage - Munin plugin to monitor darwin cpu 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 CPU usage 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" ) {
	print "graph_title CPU usage\n";
	print "graph_args --base 1000 -r --lower-limit 0 --upper-limit 100\n";
	print "graph_vlabel %\n";
	print "graph_scale no\n";
	print "graph_category system\n";
	print "sys.label system\n";
	print "sys.type GAUGE\n";
	print "sys.min 0\nsys.draw AREA\n";
	print "user.label user\n";
	print "user.type GAUGE\n";
	print "user.min 0\nuser.draw STACK\n";
	print "idle.label idle\n";
	print "idle.type GAUGE\n";
	print "idle.min 0\nidle.draw STACK\n";
	exit 0;
    }
}

@top = `top -l1 -n0 -u`;
$quit = 0;
for ( $i = 1;  ($i < $#top and $quit == 0); $i++ ) {
	if ( $top[$i] =~ /^CPU/ ) {
		$usr = $sys = $idl = $top[$i];
		$usr =~ s/^.+?: (\d+\.\d+)\% user.+$/$1/;
		chomp($usr);
		$sys =~ s/^.+?, (\d+\.\d+)\% sys.+$/$1/;
		chomp($sys);
		$idl =~ s/^.+?, (\d+\.\d+)\% idle.+$/$1/;
		chomp($idl);
		print "sys.value " . $sys . "\n";
		print "user.value " . $usr . "\n";
		print "idle.value " . $idl . "\n";
		$quit = 1;
	}
}




# vim:syntax=perl
