require "rubygems"
require "rake"

def tasks
  Rake.application.instance_eval { @tasks }
end

def current_scope
  Rake.application.instance_eval { @scope.last }
end

def task_defined?(task_name)
  Rake::Task.task_defined?(task_name)
end

def remove_tasks(*task_names)
  task_names.flatten.each do |task_name|
    remove_task(task_name)
  end
end

def remove_task(task_name)
  tasks.delete(task_name.to_s)
end

def lookup_task(task_name)
  Rake::Task[task_name] rescue nil
end

def rakecall(task_name)
  lookup_task(task_name).invoke
end

def override_task(task_args, &block)
  task_name, deps = Rake.application.resolve_args(task_args)
  original = lookup_task(task_name)
  orgproc = lambda {} # nop
  if original
    Rake.application.last_comment = original.comment
    deps |= original.prerequisites
    orgproc = lambda{ original.execute }
  end

  remove_task(task_name)
  Rake::Task.define_task(task_name => deps) do |t|
    block.call(t, orgproc)
  end
end

def task_for_windows(task_args, &block)
  override_task(task_args) do |t, org|
    if windows?
      block.call(t)
    else
      org.call
    end
  end
end
