#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.  The
# ASF licenses this file to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance with the
# License.  You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
# License for the specific language governing permissions and limitations
# under the License.

# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.

require 'rake'
require 'rake/testtask'
require 'rubygems/package_task'

begin
  require "bundler"
  Bundler.setup
rescue LoadError
  $stderr.puts "Please install bundler with 'gem install bundler'"
  exit(1)
end

$top_srcdir = File.dirname(__FILE__)
$:.unshift File.join($top_srcdir, 'lib')

begin
  require 'yard'
  YARD::Rake::YardocTask.new do |t|
    t.files   = ['lib/**/*.rb', '*.rb']   # optional
  end
rescue LoadError
end

spec = Gem::Specification.load('deltacloud-core.gemspec')

Gem::PackageTask.new(spec) do |pkg|
  pkg.need_tar = true
end

namespace :mock do
  namespace :fixtures do
    desc "Setup Mock driver fixtures"
    task 'setup' do
      if ENV["DELTACLOUD_MOCK_STORAGE"]
        storage_root = ENV["DELTACLOUD_MOCK_STORAGE"]
      elsif ENV["USER"]
        storage_root = File::join("/var/tmp", "deltacloud-mock-#{ENV["USER"]}")
      else
        raise "Please set either the DELTACLOUD_MOCK_STORAGE or USER environment variable"
      end
      data = Dir::glob(File::join(File::dirname(__FILE__), "lib", "deltacloud", "drivers", "mock", "data", "*"))
      FileUtils::mkdir_p(storage_root, :verbose => true)
      FileUtils::cp_r(data, storage_root, :verbose => true)
    end

    desc "Remove Mock driver fixtures"
    task 'clean' do
      if ENV["DELTACLOUD_MOCK_STORAGE"]
        storage_root = ENV["DELTACLOUD_MOCK_STORAGE"]
      elsif ENV["USER"]
        storage_root = File::join("/var/tmp", "deltacloud-mock-#{ENV["USER"]}")
      else
        raise "Please set either the DELTACLOUD_MOCK_STORAGE or USER environment variable"
      end
      FileUtils::rm_rf(storage_root, :verbose => true)
    end

    desc "Reset Mock driver fixtures"
    task 'reset' do
      Rake::Task["mock:fixtures:clean"].reenable
      Rake::Task["mock:fixtures:clean"].invoke
      Rake::Task["mock:fixtures:setup"].reenable
      Rake::Task["mock:fixtures:setup"].invoke
    end

  end
end

desc "List the routes defined by Rabbit"
[:cimi, :deltacloud].each do |frontend|
  namespace frontend do
    desc "Print all routes defined for #{frontend.to_s.capitalize}"
    task :routes do
      ENV['API_FRONTEND'] = frontend.to_s
      load File.join(File.dirname(__FILE__), 'config.ru')
      f_class = (frontend == :cimi) ? CIMI : Deltacloud
      f_class.collections.each do |c|
        puts "\033[1;32;m#{c.name}\33[0m"
        c.operations.each do |o|
          puts "\033[1;37m%6s\033[0m :%-10s %-35s (%s)" % [
            o.http_method.to_s.upcase,
            o.operation_name,
            o.full_path,
            Sinatra::Rabbit.generate_url_helper_for(c, o)[1]
          ]
        end
        unless c.collections.empty?
          puts
          c.collections.each do |s|
            puts "\033[1;32;m#{s.name}\33[0m"
            s.operations.each do |o|
              puts "\033[1;37m%6s\033[0m :%-10s %-35s (%s)" % [
                o.http_method.to_s.upcase,
                o.operation_name,
                o.full_path,
                o.description[0..100]
              ]
            end
          end
        end
        puts
      end
    end
  end
end

desc 'List Deltacloud routes'
task :routes do
  Rake::Task['deltacloud:routes'].invoke
end

DRIVERS = [:mock, :ec2, :rhevm, :google, :gogrid, :openstack]

desc 'Run all tests'
task :test do

  Rake::Task["mock:fixtures:reset"].invoke
  puts "\n[ \033[1;37;mrake test:base\33[0m ]\n"
  Rake::Task["test:base"].invoke
  Rake::Task["mock:fixtures:reset"].invoke
  puts "\n[ \033[1;37;mrake test:ec2\33[0m ]\n"
  Rake::Task["test:ec2"].invoke
  puts "\n[ \033[1;37;mrake test:cimi:models\33[0m ]\n"
  Rake::Task["test:cimi:models"].invoke
  DRIVERS.each do |driver|
    puts "\n[ \033[1;37;mrake drivers:#{driver}\33[0m ]\n"
    Rake::Task["test:drivers:#{driver}"].invoke
  end
end

namespace :test do

  desc "Run all tests and generate code coverage report"
  task :coverage do
    ENV['COVERAGE'] = '1'
    puts "[ \033[1;37;mCoverage report will be generated to server/coverage\33[0m ]\n\n"
    Rake::Task["test"].invoke
  end

  namespace :drivers do

    DRIVERS.each do |driver|
      Rake::TestTask.new(driver) do |t|
        t.ruby_opts << '-r./tests/test_helper.rb'   # Load SimpleCov when COVERAGE=1 is set
        unless RUBY_VERSION < '1.9.0'
          t.loader = :testrb
        end
        t.test_files = FileList["tests/drivers/#{driver}/*test.rb"]
      end
    end

  end

  Rake::TestTask.new(:base) do |t|
    unless RUBY_VERSION < '1.9.0'
      t.loader = :testrb
    end
    t.test_files = FileList[
      'tests/helpers/core_ext/*test.rb',        # Deltacloud extensions (core_ext) and other helpers
      'tests/helpers/rack/*test.rb',            # Rack extensions Deltacloud use
      'tests/drivers/base/*test.rb',            # Deltacloud drivers API tests
      'tests/drivers/models/*test.rb',          # Deltacloud models tests
      'tests/deltacloud/*test.rb',              # Deltacloud internal API tests
      'tests/deltacloud/collections/*test.rb',  # Deltacloud collections
    ]
  end

  Rake::TestTask.new(:ec2) do |t|
    unless RUBY_VERSION < '1.9.0'
      t.loader = :testrb
    end
    t.test_files = FileList[
      'tests/ec2/*test.rb',                     # EC2 frontend internal API tests
    ]
  end

  namespace :cimi do
    Rake::TestTask.new(:models) do |t|
      unless RUBY_VERSION < '1.9.0'
        t.loader = :testrb
      end
      t.test_files = FileList[
        'tests/cimi/model/*spec.rb',            # CIMI frontend serialization API tests
        'tests/cimi/collections/*test.rb',      # CIMI frontend API tests
      ]
    end
  end

end
