#!/usr/bin/ruby -w

require 'net/http'
require 'uri'
require 'rexml/document'

def getResponse(url)
   check = String.new
   ht = URI.parse(url)
   begin
      timeout(20) do
         response = Net::HTTP.get_response(ht)
         check = case response
            when Net::HTTPRedirection : " Redirect ... new URI: #{response['location']}"
            when Net::HTTPForbidden :   " Forbidden ... check URI"
            when Net::HTTPNotFound :    " Not found ... check URI"
         end
      end
   rescue TimeoutError
      check = " Connection timed out"
   rescue SocketError => socket_error
      check = " #{ht.host} not found"
   rescue Errno::ECONNRESET, Errno::EPIPE, Errno::ECONNREFUSED
      check =  " Connection to #{ht.host} failed!"
   rescue Net::HTTPBadResponse
      check = " #{ht.host} sends bad HTTP data"
   end
   url + check if check
end

def parse_opml(opml_node)
  feeds = Array.new
  opml_node.elements.each('outline') do |el|
    el.elements.each('outline') do |fe|
      if (fe.attributes['xmlUrl'])
         feeds.push(fe.attributes['xmlUrl'])
      end
    end
  end
  return feeds
end

begin
   opml = REXML::Document.new(File.read(ARGV.first))
   feeds = parse_opml(opml.elements['opml/body'])
   feeds.each do |feed|
      resp = getResponse(feed)
      puts resp if resp
   end 
rescue NoMethodError
   puts "File #{ARGV.first} could not be parsed!"
rescue
   puts "File #{ARGV.first} not found!"
end

