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

#FIXME: revisit the blacklisted spec/higher_level_api/integration/message_properties_access_spec.rb
# A bug was reported upstream: https://github.com/ruby-amqp/bunny/issues/594

$blacklist =%w[
  spec/higher_level_api/integration/message_properties_access_spec.rb
  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
  spec/higher_level_api/integration/toxiproxy_spec.rb
  spec/higher_level_api/integration/connection_spec.rb
  spec/higher_level_api/integration/queue_declare_spec.rb
  spec/issues/issue549_spec.rb
  spec/unit/concurrent/synchronized_sorted_set_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
configfile = File.join($tmpdir, 'rabbitmq.conf')
conf = File.read('spec/config/rabbitmq.conf').gsub('/spec/tls', File.expand_path('spec/tls'))
File.open(configfile, 'w') do |f|
  f.write(conf)
end
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' => configfile,
  'RABBITMQ_ENABLED_PLUGINS_FILE' => File.expand_path('spec/config/enabled_plugins'),
  'RABBITMQ_SCHEMA_DIR' => File.join($tmpdir, 'schema'),
  'RABBITMQ_GENERATED_CONFIG_DIR' => File.join($tmpdir, 'config'),
  '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 run(*cmd)
  system(*cmd) or fail("command failed: %s" % cmd.inspect)
end

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

  pidfile = File.join($tmpdir, 'mnesia', 'bunny@' + Socket.gethostname + '.pid')
  run('/usr/lib/rabbitmq/bin/rabbitmqctl', 'wait', pidfile)

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

def stop_rabbitmq_server
  run('/usr/lib/rabbitmq/bin/rabbitmqctl', 'stop')
  run('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
