require 'rototiller'

namespace :ci do
  namespace :test do

    desc 'Tests at the component level for the pe-r10k project'
    task :component => [:check_pe_r10k_env_vars] do
      Rake::Task[:beaker].invoke
    end
  end
end

desc 'Run tests against a packaged PE build'
task :acceptance do
  @acceptance_pre_suite = 'pre-suite'
  Rake::Task[:beaker].invoke
end

desc 'The acceptance tests for r10k, run in the beaker framework'
rototiller_task :beaker => [:beaker_hostgenerator] do |t|

  common_setup = <<-EOS
pre-suite/00_pe_install.rb,
component/pre-suite/05_install_dev_r10k.rb,
pre-suite/10_git_config.rb,
pre-suite/20_pe_r10k.rb,
EOS
  common_setup.gsub!("\n", '')

  flags = [
      {:name => '--hosts', :default => 'configs/generated', :override_env => 'BEAKER_HOST'},
      {:name => '--keyfile', :default => "#{ENV['HOME']}/.ssh/id_rsa-acceptance", :override_env => 'BEAKER_KEYFILE'},
      {:name => '--load-path', :default => 'lib'},
      {:name => '--pre-suite', :default => @acceptance_pre_suite || common_setup, :override_env => 'BEAKER_PRE_SUITE'},
      {:name => '--tests', :default => 'tests', :override_env => 'BEAKER_TESTS'},
      {:name => '--preserve-hosts', :default => 'onfail', :override_env => 'BEAKER_PRESERVE_HOSTS'},
  ]
  t.add_flag(*flags)

  t.add_env do |env|
    env.name = 'PE_FAMILY'
    env.message = 'The puppet enterprise major branch to install from'
  end

  t.add_env do |env|
    env.name = 'pe_dist_dir'
    env.message = 'The location to download PE from, for example "https://artifactory.delivery.puppetlabs.net/artifactory/generic_enterprise__local/20XX.X/ci-ready"'
    ENV['pe_dist_dir'] ||= "https://artifactory.delivery.puppetlabs.net/artifactory/generic_enterprise__local/#{ENV['PE_FAMILY']}/ci-ready"
  end

  t.add_env do |env|
    env.name = 'GIT_PROVIDER'
    env.message = 'The git provider that r10k should use on a SUT'
  end

  t.add_command({:name => 'beaker --debug', :override_env => 'BEAKER_EXECUTABLE'})
end

desc 'Generate a host configuration used by Beaker'
rototiller_task :beaker_hostgenerator do |t|
  if ENV['BEAKER_HOST'].nil?
    t.add_command do |c|
      c.name = 'beaker-hostgenerator'
      c.argument = '> configs/generated'
    end

    # This is a hack :(
    t.add_flag(:name => '', :default => 'centos6-64mdca-64.fa', :override_env => 'TEST_TARGET')

    t.add_flag(:name => '--global-config', :default => '{forge_host=forge-aio01-petest.puppetlabs.com}', :override_env => 'BHG_GLOBAL_CONFIG')
  end
end

rototiller_task :check_pe_r10k_env_vars do |t|
  t.add_env(:name => 'SHA', :message => 'The sha for pe-r10k')
end

