#!/usr/bin/perl

use strict;
use XML::Simple;

my $WOEID = 854823; # Yahoo! "Where On Earth Identifier" for Riga, Latvia

my $ZABBIX_SENDER = "/home/zabbix/bin/zabbix_sender";
my $ZABBIX_SERVER = "127.0.0.1";
my $ZABBIX_HOSTNAME = "a host Template_Weather is linked to";

my $xml = `curl --silent 'http://weather.yahooapis.com/forecastrss?w=$WOEID&u=c'`;
die "Could not fetch weather forecast: $!\n" if $? != 0;

my $weather = new XML::Simple->XMLin($xml)->{channel};

sub send_value {
  print SENDER qq("$ZABBIX_HOSTNAME" $_[0] "$_[1]"\n);
}

open(SENDER, "| $ZABBIX_SENDER --zabbix-server $ZABBIX_SERVER --input-file -") || die "Cannot execute zabbix_sender: $!\n";

my $location = $weather->{'yweather:location'};

send_value("weather.location[city]", $location->{city});
send_value("weather.location[country]", $location->{country});

my $wind = $weather->{'yweather:wind'};

send_value("weather.wind[chill]", $wind->{chill});
send_value("weather.wind[direction]", $wind->{direction});
send_value("weather.wind[speed]", $wind->{speed});

my $atmosphere = $weather->{'yweather:atmosphere'};

send_value("weather.atmosphere[humidity]", $atmosphere->{humidity});
send_value("weather.atmosphere[pressure]", $atmosphere->{pressure});
send_value("weather.atmosphere[visibility]", $atmosphere->{visibility});

my $astronomy = $weather->{'yweather:astronomy'};

send_value("weather.astronomy[sunrise]", $astronomy->{sunrise});
send_value("weather.astronomy[sunset]", $astronomy->{sunset});

my $condition = $weather->{item}->{'yweather:condition'};

send_value("weather.condition[text]", $condition->{text});
send_value("weather.condition[code]", $condition->{code});
send_value("weather.condition[temperature]", $condition->{temp});

my $count = 0;
my @forecasts = @{$weather->{item}->{'yweather:forecast'}};

foreach my $forecast (@forecasts) {
  last if (++$count > 2);
  my $day = ($count == 1 ? "today" : "tomorrow");
  send_value("weather.forecast[$day,text]", $forecast->{text});
  send_value("weather.forecast[$day,code]", $forecast->{code});
  send_value("weather.forecast[$day,temperature,low]", $forecast->{low});
  send_value("weather.forecast[$day,temperature,high]", $forecast->{high});
}

close(SENDER);

