#!/usr/bin/env ruby

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

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

stats = LKP::Stats.new

# udf/102 - output mismatch (see /lkp/benchmarks/xfstests/results//udf/102.out.bad)
TEST_PATTERN = '(generic|ext4|xfs|btrfs|udf|ocfs2)\/(\d\d\d)'.freeze

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

  case line
  when /^#{TEST_PATTERN}\s+\[failed, /, # btrfs/005 [failed, exit status 1]- output mismatch (see /lkp/benchmarks/xfstests/results//btrfs/005.out.bad)
       /^#{TEST_PATTERN}\s+- output mismatch/, # btrfs/158 - output mismatch (see /lkp/benchmarks/xfstests/results//btrfs/158.out.bad)
       /^#{TEST_PATTERN}\s+_check_dmesg: something found in dmesg/, # xfs/385 _check_dmesg: something found in dmesg (see /lkp/benchmarks/xfstests/results//xfs/385.dmesg)
       /^_check_generic_filesystem: filesystem on .+ is inconsistent \(see .+\/([a-z]+)\/([0-9]+)\.full\)/,
       /^#{TEST_PATTERN}\s+_check.+: filesystem on .+ is inconsistent/ # btrfs/002 _check_btrfs_filesystem: filesystem on /dev/sda2 is inconsistent
    stats.add "#{$1}.#{$2}", 'fail'
  when /^#{TEST_PATTERN}\s+\[not run\]/
    # xfs/161 [not run] Assuming DMAPI modules are not loaded
    stats.add "#{$1}.#{$2}", 'skip'
  when /^#{TEST_PATTERN}\s+(\d+)s/
    # btrfs/011        3434s
    stats.add "#{$1}.#{$2}", 'pass'
  # Ran: ext4/001 ext4/003 ext4/005 ext4/007 ext4/010 ext4/012 ext4/014 ext4/016 ext4/018 ext4/020 ext4/022 ext4/024 ext4/026
  # Failures: ext4/007 ext4/045
  # Not run: xfs/161 xfs/426
  # Above summarized lines only occur once in the end, which will be used to check
  # possible logic issue. And use detail line to analyze test status, in case the
  # summarized line is not existed due to issue like soft timeout or panic

  when /^Ran: (.*)/
    # Ran includes all the cases no matter it is 'pass', 'fail' or 'skip'
    # Cannot merge with next 'when'
    # because in 'Ran' case don't need stats_type and shouldn't call select method
    summary_ran_cases = $1.tr('/', '.').split
    stats_ran_cases = stats.keys
    unless summary_ran_cases == stats_ran_cases
      log_error 'summarized ran != stats ran'
      exit 1
    end
  when /^(Failures|Not run): (.*)/
    stats_type = $1.include?('Failures') ? 'fail' : 'skip'
    summary_cases = $2.tr('/', '.').split
    stats_cases = stats.select { |_key, value| value == stats_type }.keys
    # select method will return an empty hash when there is no matched value, won't return nil
    unless summary_cases == stats_cases
      log_error "summarized #{stats_type} != stats #{stats_type}"
      exit 1
    end
  end
end

stats.dump
