<?php
    header
('Content-Type: application/json');

    
$data = array();
    
$cache_prefix "https://newscache.vagabond.net.nz/news/";
    
$live_prefix "http://on-demand.radionz.co.nz/news/";
    
//what's the current time?
    
$current_time date("U");

    
//format the date / time to how Radio NZ names their file
    
$time_string date("Ymd-H00"$current_time);
    
$filename $time_string "-048.mp3";
    
$file_url $cache_prefix $filename;


    if(!
UR_exists($file_url))
    {
        
//the file might exist online but not have been retrieved and normalised yet.
        //  let's see. If so, we'll send them the live file
        
$file_url $live_prefix $filename;
        if(!
UR_exists($file_url))
        {
            
//The news for this hour hasn't been posted yet, see if the bulletin for the hour before exists
            
$current_time -= 3600;
            
$time_string date("Ymd-H00"$current_time);
            
$filename $time_string "-048.mp3";
            
//is the previous hour cached?
            
$file_url $cache_prefix $filename;
            if(!
UR_exists($file_url))
            {
                
//we don't have it cached. This isn't going well.
                //let's see if it's available at the live site
                
$file_url $live_prefix $filename;
                if(!
UR_exists($file_url))
                {
                    
//that doesn't exist either (maybe they changed the naming, maybe they're on to us!)
                    //can't see a method to supply an error message. Alexa will say it's offline anyway
                    
die;
                }
            }
        }
    }

    
//format the update time as UTC like Amazon expects
    
$utc_time $current_time date("Z");
    
$update_time date("Y-m-d"$utc_time) . "T" date("H:i:s"$utc_time) . ".0Z";

    
$data["uid"] = "000004";
    
$data["updateDate"] = $update_time;
    
$data["titleText"] = "Radio New Zealand News";
    
$data["mainText"] = "";
    
$data["streamUrl"] = $file_url;
    
$data["redirectionUrl"] = "http://www.radionz.co.nz/";

    echo 
json_encode($data);

function 
UR_exists($url){
    
//function copied from Patrick at StackOverflow
    //http://stackoverflow.com/questions/7684771/how-check-if-file-exists-from-the-url
   
$headers=get_headers($url);
   return 
stripos($headers[0],"200 OK")? true:false;
}
?>