require File.expand_path File.join(File.dirname(__FILE__), "ruby_base.rb")

class BuildWise::Builder::Rake < BuildWise::Builder::RubyBase
  attr_accessor :build_log

  def initialize(config)
    super(config, "rake")
  end


  def run_task(build_step, log_file)
    task_name = build_step.name
    target = build_step.task
    cmd = "rake"    

    if log_file


      full_cmd = cmd + " " + target.to_s      
      begin
        puts "#{Time.now} [INFO] Run Rake task '#{target.to_s}'"


        exit_value = ::CommandLine.execute(full_cmd.split(" "), {:stdout => log_file, :stderr => log_file, :env => @config.build_environment_variables})
      

        @output = File.read(log_file)
      ensure
        
      end
    else
      puts "#{Time.now} [DEBUG] Rake Exit Value from execution #{cmd}"
      @output = `#{cmd} #{target} 2>&1`
    end
    
    result = successful?
    raise "Failed on task: #{target}" unless result
    return result      
  end
  
  def successful?
    
    was_successful = ($?.exitstatus == 0 && !@output.include?("aborted!") && !@output.include?("Failures:") )
    puts "check passing 1: #{was_successful}"

=begin


    if was_successful       
      was_successful = !@output.include?(" failed")
      puts "check passing 2: #{was_successful}"
    end
=end
    

    was_successful &&= !@output.include?("FAILED (failures=")      
    puts "check passing 3: #{was_successful}"      
    
    puts "#{Time.now} [INFO] Calling Rake successful => #{was_successful}, exit code #{$?.exitstatus}"
    puts "#{Time.now} [INFO] Rake task output below:\n--------------\n#{@output}--------------\n"
    return was_successful
  end
end