#!/usr/bin/perl -w

# Author: William Viker <william.viker@gmail.com>
# Version: 0.1

# Non-members may check out a read-only working copy anonymously over HTTP.
# $ svn checkout http://wfrogmunin.googlecode.com/svn/trunk/ wfrogmunin-read-only

# TODO:
# * Wait a couple of hours to see if this actually works.
# * Add proper data labels for the different values possible
# * more..

use strict;
use Data::Dumper;

# INSTRUCTIONS
#
# 1. Install wfrog, get it up running with your weather station
# 2. Locate your wfrog.csv file (wfrog creates after 10 mins)
# 3. cd /etc/munin/plugins/
# 4. ln -s /usr/share/munin/plugins/wfrog wfrog_temp 
# 4. ln -s /usr/share/munin/plugins/wfrog wfrog_pressure 
# 5. etc..
# 6. reload munin-node ;-)


# In case you need to change this.

my %CONFIG = (
	'wfrogcsv' => '/var/lib/wfrog/wfrog.csv',
);


my $interesting;

if ($0 =~ m#wfrog_(\w+)#) {
	$interesting = $1;	
}

else {
	print STDERR "Symlink the wfrog plugin file to wfrog_something, like wfrog_temperature, etc." . "\n";
	exit 1;
}

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

open FILE, "<", $CONFIG{'wfrogcsv'};

my $header = <FILE>;

seek( FILE, -300, 2 );
my @line = readline FILE;

$header   =~ s/[\r\n]//gs; # bah @ csv
$line[-1] =~ s/[\r\n]//gs; # --- " ---

my @Data = split /,/, $line[-1];
my @Keys = split /,/, $header;

my $GotKeyName;
my $GotKeyData;
my $cpos = 0;

for (@Keys) {
	if ($_ eq $interesting) {
		$GotKeyName = $_;
		if (defined $Data[$cpos]) {
			$GotKeyData = $Data[$cpos];
		}
	}
	$cpos++;
}

unless (defined $GotKeyName) {
	print STDERR "Could not find any data on '$interesting'. Does the file contain any data?\n";
	exit 1;
}

my $graph_name = $GotKeyName;
$graph_name =~ s/[^a-z]//gi;

if (defined $ARGV[0] && $ARGV[0] eq 'config') {
	print     "graph_title WFrog $GotKeyName\n"
		. "graph_args --base 1000 -l 0\n"
		. "graph_vlabel Value\n"
		. "graph_scale yes\n"
		. "graph_category sensors\n"
	#	. "graph_printf %3.0lf\n"
		. "$graph_name.label $GotKeyName\n"
		. "$graph_name.draw AREASTACK\n";

	exit 0;
}

print "$graph_name.value $GotKeyData\n";
