#!/usr/bin/perl
#
# Munin plugin for graphing the weather information provided by BuienRadar (The Netherlands)
#
# Copyright (C) 2011 - Rowdy Schwachofer (http://rowdy.nl)
# BuienRadar: http://www.buienradar.nl
#
#
# This program is free software: you can redistribute it and/or modify it under the terms of the 
# GNU General Public License as published by the Free Software Foundation, either version 3 of 
# the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without 
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program.
# If not, see <http://www.gnu.org/licenses/>.
#
#
### Requirements
# This plugin uses the perl module LibXML. You should have it installed... :)
#
#
#
### Configuration example
# Use these settings in your client config in /etc/munin/plugin-conf.d/munin-node
# For the language you can use 'nl' (Dutch) or 'en'. O well, everything except 'nl' will just show
# the english version. :)
#
# [buienradar*]
# env.language         = 'en'
# env.temperature      = 'yes'
# env.temperature10cm  = 'yes'
# env.humidity         = 'yes'
# env.windspeedMS      = 'yes'
# env.windspeedBF      = 'yes'
# env.airpressure      = 'yes'
# env.view             = 'yes'
# env.gusts            = 'yes'
# env.rain             = 'yes'
#
#
# 
### Installation Example
# Below is a example to monitor station Venlo (6391). Codes for the station can be seen at the end of 
# this source or can be show with the command './buienradar_ stations'
#
# wget -O /usr/lib/munin/plugins/buienradar_ http://exchange.munin-monitoring.org/plugins/buienradar_/version/1/download
# chmod a+x /usr/lib/munin/plugins/buienradar
# ln -s /usr/lib/munin/plugins/buienradar_ /etc/munin/plugins/buienradar_6391
# /etc/init.d/munin-node restart
#

use strict;
use warnings;
use XML::LibXML;
use Data::Dumper;


# Getting the environment variabeles
my $LAN      = $ENV{language}        || "en";
my $TMP      = $ENV{temperature}     || "yes";
my $TMP10CM  = $ENV{temperature10cm} || "yes";
my $HUM      = $ENV{humidity}        || "yes";
my $WSMS     = $ENV{windspeedMS}     || "yes";
my $WSBF     = $ENV{windspeedBF}     || "yes";
my $AP       = $ENV{airpressure}     || "yes";
my $VIEW     = $ENV{view}            || "yes";
my $GUSTS    = $ENV{gusts}           || "yes";
my $RAIN     = $ENV{rain}            || "yes";


# Do we need to print the station list?
if (defined $ARGV[0] and $ARGV[0] eq "stations") {
    die print_stations();
}


# Getting the station
my $station = "";
if ($0 =~ /buienradar_(\w+)$/i) {
    $station = $1;
} elsif (not defined $ARGV[0] or ($ARGV[0] ne "config" and $ARGV[0] ne "stations")) {
    # Let's show a nice error message and display the list of stations
    die  "Error:\n"
        ."We need to know what station you want to monitor. Please set your station this way \n\n"
        ."  ln -s /usr/lib/munin/plugins/buienradar_ /etc/munin/plugins/buienradar_STATIONCODE\n\n"
        .print_stations();
}


# Let's first try to find the station that is requested
my $xml = "http://xml.buienradar.nl";
my $parser = XML::LibXML->new();
my $doc = $parser->parse_file($xml);
my $stationNode = "//weerstation[stationcode/text() = '$station']/";
my $stationName = "Regio ".$doc->findvalue($stationNode."/stationnaam/\@regio")." (".$doc->findnodes($stationNode."/stationnaam/text()").")";

if($stationName eq "") {
    # Darn, no station name found. This means we don't provided a correct id.
    die  "Error:\n"
        ."You have provided an invalid station code. (".$station.") Please use a correct one.\n\n"
        .print_stations(); 
}


# Output for config
if(defined $ARGV[0] && $ARGV[0] eq 'config') {
    print "graph_title ".$stationName."\n";
    print "graph_category Weather\n";
    if($LAN eq "nl") {
        # Dutch Language
        if($TMP      eq "yes") { print "tmp.label Temperatuur (C)\n"; }
        if($TMP10CM  eq "yes") { print "tmp10cm.label Temperatuur op 10cm (C)\n"; }
        if($HUM      eq "yes") { print "hum.label Luchtvochtigheid\n"; }
        if($WSMS     eq "yes") { print "wsms.label Windsnelheid (ms)\n"; }
        if($WSBF     eq "yes") { print "wsbf.label Windsnelheid (Bft)\n"; }
        if($AP       eq "yes") { print "ap.label Luchtdruk\n"; }
        if($VIEW     eq "yes") { print "view.label Zichtmeters\n"; }
        if($GUSTS    eq "yes") { print "gusts.label Windstoten (ms)\n"; }
        if($RAIN     eq "yes") { print "rain.label Regen (mm p/u)\n"; }
    }
    else {
        # All other languages
        if($TMP      eq "yes") { print "tmp.label Temperature (C)\n"; }
        if($TMP10CM  eq "yes") { print "tmp10cm.label Temperature 10cm (C)\n"; }
        if($HUM      eq "yes") { print "hum.label Humidity\n"; }
        if($WSMS     eq "yes") { print "wsms.label Wind speed (ms)\n"; }
        if($WSBF     eq "yes") { print "wsbf.label Wind Speef (Bft)\n"; }
        if($AP       eq "yes") { print "ap.label Air pressure\n"; }
        if($VIEW     eq "yes") { print "view.label View (m)\n"; }
        if($GUSTS    eq "yes") { print "gusts.label Wind gusts (ms)\n"; }
        if($RAIN     eq "yes") { print "rain.label Rain (mm p/h)\n"; }
    }
    exit 0;
}


# Print the values
if($TMP      eq "yes") { print "tmp.value ".$doc->findnodes($stationNode."/temperatuurGC/text()")."\n"; }
if($TMP10CM  eq "yes") { print "tmp10cm.value ".$doc->findnodes($stationNode."/temperatuur10cm/text()")."\n"; }
if($HUM      eq "yes") { print "hum.value ".$doc->findnodes($stationNode."/luchtvochtigheid/text()")."\n"; }
if($WSMS     eq "yes") { print "wsms.value ".$doc->findnodes($stationNode."/windsnelheidMS/text()")."\n"; }
if($WSBF     eq "yes") { print "wsbf.value ".$doc->findnodes($stationNode."/windsnelheidBF/text()")."\n"; }
if($AP       eq "yes") { print "ap.value ".$doc->findnodes($stationNode."/luchtdruk/text()")."\n"; }
if($VIEW     eq "yes") { print "view.value ".$doc->findnodes($stationNode."/zichtmeters/text()")."\n"; }
if($GUSTS    eq "yes") { print "gusts.value ".$doc->findnodes($stationNode."/windstotenMS/text()")."\n"; }
if($RAIN     eq "yes") { print "rain.value ".$doc->findnodes($stationNode."/regenMMPU/text()")."\n"; }



# Station codes
# Static, I know I could do this dynamically, but since they don't change regularly I choose this way
# so I could present two nice rows whitout having to write a buncgh of code... :P
sub print_stations {
    return  "Available station codes, updated last on April 4th 2011\n\n"
           ." [6391] Venlo (Station Arcen)                         [6275] Arnhem (Station Arnhem)\n"
           ." [6249] Berkhout (Station Berkhout)                   [6308] Cadzand (Station Cadzand)\n"
           ." [6260] Utrecht (Station Utrecht)                     [6235] Den Helder (Station Den Helder)\n"
           ." [6370] Eindhoven (Station Eindhoven)                 [6321] Noordzee (Station Euro platform)\n"
           ." [6350] Gilze Rijen (Station Gilze Rijen)             [6323] Goes (Station Goes)\n"
           ." [6283] Oost-Overijssel (Station Groenlo-Hupsel)      [6280] Groningen (Station Groningen)\n"
           ." [6315] Oost-Zeeland (Station Hansweert)              [6278] Zwolle (Station Heino)\n"
           ." [6356] Gorinchem (Station Herwijnen)                 [6330] Hoek van Holland (Station Hoek van Holland)\n"
           ." [6311] Zuid-Zeeland (Station Hoofdplaat)             [6279] Hoogeveen (Station Hoogeveen)\n"
           ." [6251] Wadden (Station Hoorn Terschelling)           [6258] Enkhuizen-Lelystad (Station Houtribdijk)\n"
           ." [6285] Schiermonnikoog (Station Huibertgat)          [6209] IJmond (Station IJmond)\n"
           ." [6225] IJmuiden (Station IJmuiden)                   [6210] Katwijk (Station Katwijk)\n"
           ." [6277] Noord-Groningen (Station Lauwersoog)          [6320] Goeree (Station LE Goeree)\n"
           ." [6270] Leeuwarden (Station Leeuwarden)               [6269] Lelystad (Station Lelystad)\n"
           ." [6348] West-Utrecht (Station Lopik-Cabauw)           [6380] Maastricht (Station Maastricht)\n"
           ." [6273] Noordoostpolder (Station Marknesse)           [6286] Oost-Groningen (Station Nieuw Beerta)\n"
           ." [6312] Oosterschelde (Station Oosterschelde)         [6344] Rotterdam (Station Rotterdam)\n"
           ." [6343] Rotterdam Haven (Station Rotterdam Geulhaven) [6316] Schaar (Station Schaar)\n"
           ." [6240] Amsterdam (Station Schiphol)                  [6324] Midden-Zeeland (Station Stavenisse)\n"
           ." [6267] West-Friesland (Station Stavoren)             [6229] Texel (Station Texelhors)\n"
           ." [6331] Tholen (Station Tholen)                       [6290] Twente (Station Twente)\n"
           ." [6313] West-Zeeland (Station Vlakte aan de Raan)     [6242] Vlieland (Station Vlieland)\n"
           ." [6310] Vlissingen (Station Vlissingen)               [6375] Uden (Station Volkel)\n"
           ." [6319] Terneuzen (Station Westdorpe)                 [6248] Hoorn (Station Wijdenes)\n"
           ." [6257] Wijk aan Zee (Station Wijk aan Zee)           [6340] Woensdrecht (Station Woensdrecht)\n"
           ." [6239] Noordzee (Station Zeeplatform F-3)            [6252] Noordzee (Station Zeeplatform K13)\n";
}