class Raykit::Command

def run

def run
  # puts '---running---'

  @start_time = Time.now
  @elapsed = 0
  timer = Timer.new
  if @timeout.zero?
    @output, @error, process_status = Open3.capture3(@command)
    @exitstatus = process_status.exitstatus
  else
    # =================================================

    #puts "@timeout is #{@timeout}"

    Open3.popen3(@command, chdir: @directory) do |_stdin, stdout, stderr, thread|
      tick = 1
      pid = thread.pid
      start = Time.now
      while ((Time.now - start) < @timeout) && thread.alive?
        Kernel.select([stdout, stderr], nil, nil, tick)
        begin
          @output << stdout.read_nonblock(BUFFER_SIZE)
          #@error << stderr.read_nonblock(BUFFER_SIZE)

        rescue IO::WaitReadable
        rescue EOFError
          #puts "rescue block entered"

          @exitstatus = thread.value.exitstatus
          until stdout.eof?
            @output << stdout.read_nonblock(BUFFER_SIZE)
          end
          until stderr.eof?
            @error << stderr.read_nonblock(BUFFER_SIZE)
          end
          break
        end
        #begin

        #  @output << stdout.read_nonblock(BUFFER_SIZE)

        #  @error << stderr.read_nonblock(BUFFER_SIZE)

        #rescue IO::WaitReadable

        #rescue EOFError

        #  @exitstatus = thread.value.exitstatus

        #  until stdout.eof?

        #    @output << stdout.read_nonblock(BUFFER_SIZE)

        #  end

        #  until stderr.eof?

        #    @error << stderr.read_nonblock(BUFFER_SIZE)

        #  end

        #  break

        #end

      end
      sleep 1
      if thread.alive?
        if Gem.win_platform?
          `taskkill /f /pid #{pid}`
        else
          Process.kill("TERM", pid)
        end
        @exitstatus = 5
        @error = +"timed out"
      else
        @exitstatus = thread.value.exitstatus
      end
    end
    # =================================================

  end
  @elapsed = timer.elapsed
  if @logging_enabled
    log
    if @exitstatus != 0
      to_log_event.to_seq
    else
      # puts '---logging---'

      unless @success_log_level.nil?
        e = to_log_event
        e["Level"] = "Verbose" if @success_log_level == "Verbose"
        e["Level"] = "Debug" if @success_log_level == Logger::DEBUG
        e["Level"] = "Information" if @success_log_level == Logger::INFO
        e["Level"] = "Warning" if @elapsed > 60 * 2
        e.to_seq
      end
    end
  end
  self
end