#!/usr/bin/env ruby
# unixbench.workload is defined as the total operations in unixbench for
# all processes/threads

LKP_SRC = ENV['LKP_SRC'] || File.dirname(File.dirname(File.realpath($PROGRAM_NAME)))

require "#{LKP_SRC}/lib/log"
require "#{LKP_SRC}/lib/string_ext"
require 'time'

# Benchmark run time format displayed as below:
# Benchmark Run: Tue Jan 01 2019 15:48:24 - 15:56:36

while (line = $stdin.gets)
  line = line.resolve_invalid_bytes

  case line.chomp!
  when /^Benchmark Run: .+ (\d+:\d+:\d+) - (\d+:\d+:\d+)$/
# We only care about the difference value between end time and start time
    start_time = Time.parse($1).to_f
    end_time = Time.parse($2).to_f
    duration = if end_time > start_time
                 end_time - start_time
               else
                 end_time + 3600 * 24 - start_time # date overflo
               end
  when /^System Benchmarks Partial Index .* INDEX$/
    line = $stdin.gets
    if line.chomp!
      lines = line.split
      throughput = lines[-2].to_f
    end
  when /^System Benchmarks Index Score .* ([0-9.]+)$/
    score = $1
  when /^System Benchmarks Index Values(\s+\S+){3}$/
    index_list = []
    while (line = STDIN.gets)
      lines = line.split
      lines_l = lines.length
      break if lines_l < 4

      index = lines[-1]
      index_value = lines[0, lines_l - 3].join('_')
      index_list.append("#{index_value}: #{index}")
    end
  end
end

if index_list.nil?
  if duration.nil? || throughput.nil?
    log_error 'unixbench: missing duration or throughput'
  else
    workload = duration * throughput
    if score
      puts "score: #{score}"
      puts "workload: #{workload}"
    else
      puts 'incomplete_result: 1'
      log_error "unixbench: missing score, check #{ENV['RESULT_ROOT']}"
    end
  end
else
  index_list.each do |index|
    puts index.to_s
  end
  puts "System_Benchmarks_Index_Score: #{score}"
end
