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

=head1 NAME

eacc - Plugin to monitor eAccelerator

=head1 CONFIGURATION EXAMPLE

/etc/munin/plugin-conf.d/eacc or other file in that dir must contain:

 [eacc]
  env.user admin
  env.pass eAccelerator
  env.host 127.0.0.1
  env.port 80
  env.page control.php


=head1 AUTHOR

falselike at gmail dot com

=head1 LICENSE

No license

=head1 MAGIC MARKERS

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

=cut

use LWP;

my $host = $ENV{'host'} || '127.0.0.1';
my $port = $ENV{'port'} || 80;
my $page = $ENV{'page'} || 'control.php';

my $user = $ENV{'user'} || 'admin';
my $pass = $ENV{'pass'} || 'eAccelerator';
my $realm = $ENV{'realm'} || 'eAccelerator control panel';

if ($#ARGV eq 0) {
	if ($ARGV[0] eq 'autoconf') {
		print "yes\n";
		exit(0);
	}

	if ($ARGV[0] eq 'config') {
		print "eAccelerator\n";
		print "graph_title eAccelerator\n";
		print "graph_category php-cgi\n";
		print "memusage.label Memory Usage %\n";
		print "memusage.warning 95\n";
		print "memusage.critical 95\n";
		print "memusage.label Memory Usage MB\n";
		print "memmax.label Cache Size MB\n";
		print "memused.label Used Memory MB\n";
		print "memfree.label Free Memory MB\n";
		print "cached.label Scripts Cached\n";
		print "removed.label Scripts Removed\n";
		print "keys.label Keys Cached\n";
		exit();
	}
}

my $ua = LWP::UserAgent->new();
$ua->credentials($host . ':' . $port, $realm, $user, $pass);
my $url = 'http://'. $host .':'. $port .'/'. $page;
my $resp = $ua->get($url);

if ($resp->is_success) {
	$b = '';
	foreach (split '\n', $resp->content) {
		if (/([\d\.]+)/) {
			$v = $1;
			# debug
			#print "$b\n$_\n";
			print "memmax.value $v\n" if $b =~ /total/i;
			if ($b =~ /in use/i) {
				print "memused.value $v\n";
				if (/([\d+\.]+)\s*%/) {
					print "memusage.value $1\n";
				}
			}
			print "memfree.value $v\n" if $b =~ /free/i;
			print "cached.value $v\n" if $b =~ /cached/i;
			print "removed.value $v\n" if $b =~ /removed/i;
			print "keys.value $v\n" if $b =~ /keys/i;
			
		}
		$b = $_;
	}
} else {
	my $ret = $resp->status_line;
	die "Authorization failed!\nPlease recheck your credentials:\n\tenv.user $user\n\tenv.pass $pass\n\n" if $ret =~ /401/;
	die "Can't get $url -- ", $ret;
}
