#!/usr/bin/env ruby

require 'rake'

rakefiles = %w[rakefile Rakefile rakefile.rb Rakefile.rb]

if rakefiles.none? { |f| File.exist?(f) } && !ARGV.include?('-f') && !ARGV.include?('--rakefile')
  require 'tmpdir'
  require 'fileutils'

  # syntethize a Rakefile
  tmpdir = Dir.mktmpdir
  rakefile = File.join(tmpdir, 'Rakefile')
  File.open(rakefile, 'w') do |f|
    f.puts 'require "chake"'
  end
  ARGV.unshift << '--rakefile' << rakefile

  # cleanup after finishing
  at_exit do
    FileUtils.rm_rf tmpdir
  end
end

class Rake::Application
  alias orig_thread_pool thread_pool
  def thread_pool # :nodoc:
    if Chake.respond_to?(:nodes)
      @thread_pool ||= Rake::ThreadPool.new(Chake.nodes.size + 1)
    else
      orig_thread_pool
    end
  end
end

Rake.application.run
