require 'tmpdir'
require 'socket'

mysql_port = nil
(1025..3600).to_a.shuffle.each do |port|
  begin
    s = TCPSocket.new 'localhost', port
    s.close
  rescue Errno::ECONNREFUSED
    mysql_port = port
    break
  end
end
unless mysql_port
  $stderr.puts "Unable to find a free TCP port to start the MySQL server."
  exit 1
end

mysql_datadir = Dir.mktmpdir('moneta')

started = system(File.expand_path('../setup-mysql.sh', __FILE__),
                 mysql_port.to_s, mysql_datadir, 'start')
unless started
  $stderr.puts "Unable to start the test MySQL server."
  exit 1
end

at_exit do
  system File.expand_path('../setup-mysql.sh', __FILE__),
         mysql_port.to_s, mysql_datadir, 'stop'
  FileUtils.remove_entry_secure mysql_datadir
end

ENV['MYSQL_TEST_SOCKET'] = File.join(mysql_datadir, 'mysql.sock')

require 'rake'
app = Rake.application
app.init
app.load_rakefile
app['test'].invoke
