#!/usr/bin/env ruby

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

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

exit unless $stdin.gets =~ /lock_stat version 0.[34]/
exit unless $stdin.gets =~ /---------------------/

names = $stdin.gets.split
names.shift
names.shift

contentions = {}
lock_stat = {}

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

  line.chomp!
  line.sub!(%r{/c/kernel-tests/src/[^/]+/}, '')
  line.sub!(%r{/kbuild/src/[^/]+/}, '')
  case line
  when / +(.+): +([0-9.]+ +[0-9.]+ +[0-9.]+ +.*)/
    lock = $1.tr(' ', '')
    values = $2.split
    values.each_with_index do |value, i|
      lock_stat["#{lock}.#{names[i]}"] ||= 0
      lock_stat["#{lock}.#{names[i]}"] += names[i] =~ /time/ ? value.to_f : value.to_i
    end
  when / +(\d+) +\[<[0-9a-f]+>\] ([a-zA-Z0-9_]+)/
    contentions[$2] ||= 0
    contentions[$2] += $1.to_i
  when /^$/
    unless contentions.empty?
      lock.chomp! '-R'
      contentions.each do |key, val|
        lock_stat["#{lock}.contentions.#{key}"] ||= 0
        lock_stat["#{lock}.contentions.#{key}"] += val
      end
      contentions.clear
    end
  end
end

lock_stat.each do |k, v|
  puts "#{k}: #{v}"
end
