#!/usr/bin/env ruby

# load a couple o' libraries here
require 'uri'
require 'net/http'

#
# check to see if a URL exists.  returns response code if it does, and
# false if it doesn't.
# 
# Examples:
#   # check a URL that does exist
#   url_exists?('http://google.com/') #=> '200'
#   # check a URL that doesn't exist
#   url_exists?('http://asdlkjalfe.asdfkljas/') #=> false
#
def url_exists?(url)
  begin 
    # parse URI, do an HTTP HEAD on requested URI
    uri = URI::parse(url)
    ret = nil
    Net::HTTP.new(uri.host, uri.port).start { |http|
      # create headers hash
      headers = {}

      # check user info
      if uri.userinfo
        headers['Authorization'] = 'Basic ' << [uri.userinfo].pack('m').strip
      end

      # check HEAD code
      ret = http.head(uri.path, headers).code
    }

    # check return code, if it's not 2xx or 3xx, return false
    ret =~ /^[23]/ ? ret : false
  rescue 
    false
  end
end

if __FILE__ == $0
  # file was called from the command-line, run some test code
  
  %w{http://google.com/
     http://pablotron.org/askljfalkdfj
     http://ruby-lang.org/
     http://asdlkjalfe.asdfkljas/
     http://slashdot.org/
     http://pablotron.org:25/
     http://pablotron.org/rss/ 
     http://asdlkfjsalkjfalekjwf.dsaf/
    }.each do |url|
     puts "#{url}: #{url_exists?(url) ? true : false}"
  end
end

