require 'gem2deb/rake/spectask'
require 'tmpdir'

$blacklist =%w[
  spec/higher_level_api/integration/connection_recovery_spec.rb
  spec/higher_level_api/integration/connection_stop_spec.rb
  spec/higher_level_api/integration/consistent_hash_exchange_spec.rb
  spec/higher_level_api/integration/tls_connection_spec.rb
] + Dir['spec/stress/*_spec.rb']

puts "****************************************************************"
puts "WARNING: THE FOLLOWING TESTS ARE BEING SKIPPED:"
puts $blacklist
puts "****************************************************************"

Gem2Deb::Rake::RSpecTask.new(:spec) do |spec|
  spec.pattern = Dir['spec/**/*_spec.rb'] - $blacklist
end

$tmpdir = Dir.mktmpdir
rabbitmq_env = {
  'HOME' => $tmpdir,
  'RABBITMQ_MNESIA_BASE' => File.join($tmpdir, 'mnesia'),
  'RABBITMQ_LOG_BASE' => File.join($tmpdir, 'log'),
  'RABBITMQ_NODE_IP_ADDRESS' => '127.0.0.1',
  'RABBITMQ_NODENAME' => 'bunny',
  'RABBITMQ_CONFIG_FILE' => './spec/config/rabbitmq.config',
  'RABBITMQ_ENABLED_PLUGINS_FILE' => './spec/config/enabled_plugins',
  'BUNNY_RABBITMQCTL' => '/usr/lib/rabbitmq/bin/rabbitmqctl',
  'BUNNY_RABBITMQ_PLUGINS' => '/usr/lib/rabbitmq/bin/rabbitmq-plugins',
}

ENV.update(rabbitmq_env)

$epmd = system('pgrep' , '-u', Process.uid.to_s, '-fa', 'epmd', :out => '/dev/null')

def start_rabbitmq_server
  fork do
    exec('/usr/lib/rabbitmq/bin/rabbitmq-server')
  end

  pidfile = File.join($tmpdir, 'mnesia', 'bunny.pid')
  system('/usr/lib/rabbitmq/bin/rabbitmqctl', 'wait', pidfile)

  system('./bin/ci/before_build')
end

def stop_rabbitmq_server
  system('/usr/lib/rabbitmq/bin/rabbitmqctl', 'stop')
  system('pkill', 'epmd') unless $epmd
  FileUtils.rm_rf($tmpdir)
end


task :default do
  start_rabbitmq_server
  begin
    Rake::Task[:spec].invoke
  ensure
    stop_rabbitmq_server
  end
end
