require 'rubygems'
require 'rake'
require 'rspec/core/rake_task'

# define tasks (default -> spec -> spec:all)
task :spec    => 'spec:all'
task :default => :spec

# 'rake spec' executes this stuff
namespace :spec do

  # find targets by looking in the 'spec' directory
  targets = []
  Dir.glob('./spec/*').each do |dir|
    next unless File.directory?(dir)
    target = File.basename(dir)
    target = "_#{target}" if target == "default"
    targets << target
  end

  # define tasks (spec:default -> spec:all)
  task :all     => targets
  task :default => :all

  # From the documentation:
  # You should not try to issue a single rspec command that would harvest and
  # run tests against multiple machines or containers. You need to issue one
  # rspec command for each of them.

  # for each target given, execute the rake task
  targets.each do |target|
    original_target = target == "_default" ? target[1..-1] : target
    desc "Run serverspec tests to #{original_target}"
    RSpec::Core::RakeTask.new(target.to_sym) do |t|
      ENV['TARGET_HOST'] = original_target
      t.pattern = "spec/#{original_target}/*_spec.rb"
    end
  end
end
