#!/usr/bin/env ruby

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

require 'yaml'
require 'optparse'
require "#{LKP_SRC}/lib/statistics"
require "#{LKP_SRC}/lib/stats"
require "#{LKP_SRC}/lib/yaml"
require "#{LKP_SRC}/lib/plot"
require "#{LKP_SRC}/lib/constant"

$options = {}

opt_parser = OptionParser.new do |opts|
  opts.banner = 'Usage: mmplot matrix1.json matrix2.json [stat_fields...] [OPTION...]'
  opts.separator ''
  opts.separator 'Example:'
  opts.separator ''
  opts.separator "mmplot #{RESULT_ROOT_DIR}/fat/dd-write/1HDD-JBOD-cfq-btrfs-100dd/x86_64-rhel/v3.10/matrix.json  \
  #{RESULT_ROOT_DIR}/fat/dd-write/1HDD-JBOD-cfq-btrfs-100dd/x86_64-rhel/matrix.json    \
  vmstat.system.in vmstat.cpu.sy perf-stat.node-stores interrupts.CPU0.LOC"

  opts.separator ''
  opts.separator 'options:'

  opts.on('-d N', '--distance N', 'threshold of changes') do |n|
    $options['distance'] = n.to_i
  end

  opts.on('-p', '--perf', 'show performance changes only') do
    $options['perf'] = true
  end

  opts.on('-c', '--concise', 'skip non-important changes') do
    $options['concise'] = true
  end

  opts.on('-r N', '--resize N', 'resize first matrix') do |n|
    $options['resize'] = n.to_i
  end

  opts.on('-v N', '--variance N', 'show variance changes larger than N times') do |n|
    $options['variance'] = n.to_i
  end

  opts.on('-o DIR', '--output DIR', 'output dir') do |dir|
    Dir.mkdir dir unless File.directory? dir
    $opt_output_path = dir
  end

  opts.on_tail('-h', '--help', 'show help message') do
    puts opts
    exit
  end
end

opt_parser.parse!(ARGV)

if ARGV.empty?
  puts opt_parser
  exit
end

path1 = ARGV[0]
ARGV.shift

if ARGV[0] && File.exist?(ARGV[0])
  path2 = ARGV[0]
  ARGV.shift
else
  path2 = nil
end

matrix1, matrix2 = load_matrices_to_compare path1, path2
exit if matrix1.nil?
exit if matrix2.nil?

if ARGV[0]
  changed_fields = ARGV
else
  changed_stats = get_changed_stats path1, path2, $options
  exit unless changed_stats && !changed_stats.empty?
  changed_fields = changed_stats.keys
end

changed_fields.reject! { |stat| function_stat?(stat) || !bisectable_stat?(stat) } if $options['concise']
mmplot(matrix1, matrix2, changed_fields)
