#!/usr/bin/perl

# Original author: Bjørn Ruberg
# Updated to Varnish 2.0/added instructions: Daniel Wirtz
#
# Installation (Debian):
# 1. Upload file to /usr/share/munin/plugins
# 2. Create symlinks:
#    ln -s /usr/share/munin/plugins/varnish2_ /etc/munin/plugins/varnish_cache
#    ln -s /usr/share/munin/plugins/varnish2_ /etc/munin/plugins/varnish_backend
#    ln -s /usr/share/munin/plugins/varnish2_ /etc/munin/plugins/varnish_shm
# 3. Restart Munin-Node:
#    /etc/init.d/munin-node restart

$arg = shift @ARGV;

%aspects = (
            'cache' => 'Cache',
            'backend' => 'Backend',
	    'shm' => 'SHM'
            );

(my $whut = $0) =~ s/^.*\_//;

# Hvis $whut IKKE fins, men $arg fins OG er noe annet enn blabla
# sÃ¥ skal den trigge

if (!$whut && $arg && $arg !~ /^(suggest|autoconf)$/) {
    print "Only 'suggest' and 'autoconf' may be used w/o symlinked name\n";
    exit 2;
} elsif (!$whut && !$arg) {
    print "Uh. Bugger.\n";
    exit 2;
}

if ($arg eq 'autoconf') {
    print "Autoconf starting...\n";
    exit 0;
} elsif ($arg eq 'suggest') {
    print "Suggest starting...\n";
    exit 0;
} elsif ($arg eq 'config') {
    $config = 1;
}

$grepfor = $aspects{$whut};
# print "Looking for $grepfor\n";

if ($config) {
    print "graph_title Varnish $grepfor usage\n";
    print "graph_args --base 1000\n";
    print "graph_vlabel Activity / \${graph_period}\n";
    print "graph_category webserver\n";
}

$i = 0;
foreach $line (`varnishstat -1`) {
    chomp $line;
    if ($line =~ /\s+(\d+)\s+\d+\.\d+\s+($grepfor.*)$/) {
        $val = $1;
        $key = $2;
        ($printkey = lc ($key)) =~ s/\s/_/g;
        if ($config) {
            print "$printkey\.label $key\n";
            print "$printkey\.type DERIVE\n";
            print "$printkey\.min 0\n";
		print "$printkey\.draw ";
	    if ($i == 0) {
		print "AREA\n";
            } else {
		print "STACK\n";
     	    }
            $i++;
        } else {
            print "$printkey\.value $val\n";
        }
    }
}
    
exit;
