#!/usr/bin/env ruby
ENV['RAILS_ENV'] = 'test'
require File.dirname(__FILE__) + '/../config/boot'
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'environment'))

Thread.abort_on_exception = true
frontend_out = nil
logger = RAILS_DEFAULT_LOGGER

frontend = Thread.new do
  puts "Starting test API at port #{FRONTEND_PORT} ..."
  frontend_out = IO.popen("cd #{RAILS_ROOT}/../api; exec ./script/server -e test -p #{FRONTEND_PORT} 2>&1")
  puts "API started with PID: #{frontend_out.pid}"
  begin
    Process.setpgid frontend_out.pid, 0
  rescue Errno::EACCES
    # what to do?
    puts "Could not set API group to root"
  end
  while frontend_out
    begin
      line = frontend_out.gets
      logger.debug line.strip unless line.blank?
    rescue IOError
      break
    end
  end
end

while true
  puts "Waiting for API to serve requests..."
  begin
    Net::HTTP.start(FRONTEND_HOST, FRONTEND_PORT) do |http|
      http.open_timeout = 15
      http.read_timeout = 15
      res = http.get('/')
      case res
        when Net::HTTPSuccess, Net::HTTPRedirection, Net::HTTPUnauthorized
          # OK
        else
          puts "API did not response nicely"
          Process.kill "INT", -frontend_out.pid
          frontend_out.close
          frontend_out = nil
          frontend.join
          exit 1
      end
    end
  rescue Errno::ECONNREFUSED, Timeout::Error
    sleep 1
    next
  end
  break
end

puts "Loading API fixtures... "
system("cd #{RAILS_ROOT}/../api ; RAILS_ENV=test rake db:fixtures:load")
puts "Test API ready."
$stdout.flush

dienow = false
trap("INT") { dienow = true }

while !dienow do
  sleep 1
end

puts "kill #{frontend_out.pid}"
Process.kill "INT", -frontend_out.pid

frontend_out.close
frontend_out = nil
frontend.join
