#!/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'))

$stderr.puts "Starting test API at port #{CONFIG['frontend_port']} ..."

Thread.abort_on_exception = true
frontend_out = nil
logger = Rails.logger

begin
  Net::HTTP.start(CONFIG['frontend_host'], CONFIG['frontend_port']) do |http|
    http.get("/test/killme")
  end
  # if we reach this, the old API has gone away - now wait for it to lay down
  sleep 2
rescue Errno::ECONNREFUSED, Errno::ENETUNREACH, Timeout::Error
  # all is good, no API no cry
end

dienow = false
lines = []
outputlines = true
frontend = Thread.new do
  cmdline = "ruby ./script/rails"
  frontend_out = IO.popen("cd #{Rails.root.join('..', 'api').to_s}; unset BUNDLE_GEMFILE; exec bundle exec #{cmdline} server -e test -p #{CONFIG['frontend_port']} 2>&1")
  while frontend_out
    begin
      line = frontend_out.gets
      lines << line if outputlines
      if line.nil? && !dienow
        puts "api died"
        puts lines.join()
        exit 1
      end
    rescue IOError
      break
    end
  end
end

while true
  puts "Waiting for API to serve requests..."
  begin
    Net::HTTP.start(CONFIG['frontend_host'], CONFIG['frontend_port']) do |http|
      http.open_timeout = 15
      http.read_timeout = 15
      res = http.get('/test/startme')
      case res
        when Net::HTTPSuccess, Net::HTTPRedirection, Net::HTTPUnauthorized
          outputlines = false
          # 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, Errno::ENETUNREACH, Timeout::Error
    sleep 1
    next
  end
  break
end

puts "Test API ready."
$stdout.flush

trap("INT") { dienow = true }

while !dienow do
  sleep 1
end

puts "got signal handler"

begin
  Net::HTTP.start(CONFIG['frontend_host'], CONFIG['frontend_port']) do |http|
    http.get("/test/killme")
  end
  # if we reach this, the API went down cleanly
  Process.wait(frontend_out.pid)
rescue Errno::ECONNREFUSED, Errno::ENETUNREACH, Timeout::Error
  # API is already gone
  puts "kill #{frontend_out.pid}"
  Process.kill "INT", frontend_out.pid
  frontend_out.close
end

frontend_out = nil
frontend.join
