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

def open(url)
  parsed_uri = URI.parse(url)
  http = Net::HTTP.new(parsed_uri.host, parsed_uri.port)
  req = Net::HTTP::Get.new(parsed_uri.request_uri)
  req.basic_auth(ENV['AUTH_USER'], ENV['AUTH_PASSWORD'].to_s) if ENV['AUTH_USER']
  http.request(req)
end

response = open(ARGV[0]) rescue nil
unless response
  i=0
  print "waiting.."
  while i < 120 and not response
    #puts 'RESPONSE:', response.inspect
    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}"
response.header.each_header {|key,value| puts "  #{key}: #{value}" }
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 (expected to find #{ARGV[3]}) - page contents:" , page_content.to_s, 'END-OF-CONTENTS'
    exit 3
  end
end

if ARGV[4] and ARGV[4] != ''
  if !page_content.to_s.include? ARGV[4]
    puts "PASS (did not find #{ARGV[4]})"
  else
    puts "FAIL (found #{ARGV[4]}) - page contents:" , page_content.to_s, 'END-OF-CONTENTS'
    exit 3
  end
end

exit 0
