require 'rubygems'
require 'chef'
require 'json'

# Load constants from rake config file.
require File.join(File.dirname(__FILE__), 'config', 'rake')

# Detect the version control system and assign to $vcs. Used by the update
# task in chef_repo.rake (below). The install task calls update, so this
# is run whenever the repo is installed.
#
# Comment out these lines to skip the update.

if File.directory?(File.join(TOPDIR, ".svn"))
  $vcs = :svn
elsif File.directory?(File.join(TOPDIR, ".git"))
  $vcs = :git
end

# Load common, useful tasks from Chef.
# rake -T to see the tasks this loads.

load 'chef/tasks/chef_repo.rake'

desc "Automated Test/Upload Task"
task :build, :cookbook do |t, args|
  ruby_version = File.read(File.join(File.dirname(__FILE__),'.rbenv-version')).chomp
  ruby_path    = "/opt/rubies/#{ruby_version}/bin"

  system <<-EOT
    export PATH=#{ruby_path}:$PATH

    bundle install --path=vendor --without development
    bundle exec strainer test #{args.cookbook}

    server_version=$(bundle exec knife cookbook list | grep " #{args.cookbook} " | awk '{print $2}')
    local_version=$(awk '/version/{print $2}' cookbooks/#{args.cookbook}/metadata.rb | tr -d "'")

    if bundle exec ruby -r solve -e "exit Solve::Version.new('$local_version') > Solve::Version.new('$server_version')" ; then
      bundle exec knife spork upload #{args.cookbook}
    else
      echo "Skipping upload because built version (${local_version}) is not greater than server version (${server_version})"
    fi
  EOT
end