#!/usr/bin/perl

use Asterisk::AGI;

my $AGI = new Asterisk::AGI;
$AGI->exec('Festival', "\"Please enter the weather ID number followed by the hash key.\"");
sleep 3;
$id = $AGI->get_data('beep', 10000, 5);

$weatherxml = "/tmp/tempweather";
$i = 0;

while ( -f $weatherxml ) {
  $weatherxml = $weatherxml . $i;
  $i++;
}

`wget -O $weatherxml http://feeds.bbc.co.uk/weather/feeds/rss/5day/id/$id.xml`;

if ( !-f $weatherxml) {
  die("Could not open $weatherxml");
}

open(WXML,"<$weatherxml") or die("Could not open $weatherxml");

while(<WXML>) {
  $line = $_;
if (($day, $weather, $maxtempc, $maxtempf, $mintempc, $mintempf) = $line=~m/<title>(.*): (.*), Max Temp: (-*[0-9]+)&#xB0;C \((-*[0-9]+)&#xB0;F\), Min Temp: (-*[0-9]+)&#xB0;C \((-*[0-9]+)&#xB0;F\)<\/title>/) {
  $AGI->exec('Festival', "\"The weather forecast for $day is $weather maximum temperture $maxtempc degrees Celsius and $maxtempf degrees Fahrenheit\, minimum temperature $mintempc degrees Celsius and $mintempf degrees Fahrenheit.\"");
}
if (($winddir, $windspeed, $visibility, $pressure, $humidity) = $line=~m/<description>Max Temp: -*[0-9]+&#xB0;C \(-*[0-9]+&#xB0;F\), Min Temp: -*[0-9]+&#xB0;C \(-*[0-9]+&#xB0;F\), Wind Direction: (.*), Wind Speed: (.*), Visibility: (.*), Pressure: (.*), Humidity: (.*),/) {
  $AGI->exec('Festival', "\"The wind speed is $windspeed in direction $direction.  Visibility is $visibility\, pressure is $pressure and humidity is $humidity\"");
}
if(($sunrise, $sunset) = $line=~m/Sunrise: (.*), Sunset: (.*)<\/description>/) {
  $AGI->exec('Festival', "\"Sunrise is at $sunrise and sunset is at $sunset\"");
  }
}

close($WXML);
unlink($WXML);
