#!/usr/bin/env ruby
require 'net/http'
require 'uri'

def open(url)
  Net::HTTP.get_response(URI.parse(url))
end

response = open(ARGV[0]) rescue nil
unless response
  i=0
  print "waiting.."
  while i < 120 and not response
    print "."
    STDOUT.flush
    i += 1
    sleep(1)
    response = open(ARGV[0]) rescue nil
  end
  unless response
    puts "\nFAIL: timed out after waiting #{i} seconds"
    exit 9
  end
  puts "\n  got url content after waiting #{i} seconds"
end

page_content = response.body

puts "  response code: #{response.code} #{response.message}"
puts "  content_type: #{response.content_type}"
puts "  body: #{page_content}"

if ARGV[1] and ARGV[1] != ''
  if ARGV[1].split(',').include?(response.code)
    puts "PASS (response code was #{response.code} which matched #{ARGV[1]})"
  else
    puts "FAIL (response code was #{response.code}, expected #{ARGV[1]})" 
    exit 1
  end
end

if ARGV[2] and ARGV[2] != ''
  if response.content_type == ARGV[2]
    puts "PASS (content type was #{response.content_type})"
  else
    puts "FAIL (content type was #{response.content_type}, expected #{ARGV[2]})" 
    exit 2
  end
end

if ARGV[3] and ARGV[3] != ''
  if page_content.to_s.include? ARGV[3]
    puts "PASS (found #{ARGV[3]})"
  else
    puts "FAIL (could not find #{ARGV[3]})" 
    exit 3
  end
end

exit 0
