require 'rubygems'
require 'nokogiri'
require 'json'

if not File.exist?('bounds.xml')
  puts `wget https://raw.github.com/gravitystorm/openstreetmap-license-change/master/bounds.xml -q`
elsif (Time.now - File.mtime('bounds.xml')) > 60*60*2  #2 hours ttl
  puts Time.now.to_i.to_s + " - " + File.mtime('bounds.xml').to_i.to_s
  File.delete('bounds.xml')
  puts `wget https://raw.github.com/gravitystorm/openstreetmap-license-change/master/bounds.xml -q`
else
  puts "Using existing bounds.xml  age:" + File.mtime('bounds.xml').to_s
end

f = File.open("bounds.xml")
doc = Nokogiri::XML(f)

bounds_array = [ ]
doc.xpath('//bounds').each do |bounds_elem|
  
  bounds_hash = { "description" => bounds_elem.attribute('description'),
                  "minlat" => bounds_elem.attribute('minlat'),
                  "minlon" => bounds_elem.attribute('minlon'),
                  "maxlat" => bounds_elem.attribute('maxlat'),
                  "maxlon" => bounds_elem.attribute('maxlon') }
  
  bounds_array << bounds_hash
end

f.close

jsonp_output = "bounds=" + bounds_array.to_json.gsub('},',"},\n")

File.open('bounds.json', 'w') {|f| f.write(jsonp_output) }

puts "DONE"

