#!/usr/bin/env ruby

require 'securerandom'
require 'nchan_tools/benchmark'
require "optparse"
require 'timers'
require 'json'
require "HDRHistogram"

verbose = false
save_csv = false
csv_columns = NchanTools::Benchmark::CSV_COLUMNS_DEFAULT
init_args = {}

opt_parser=OptionParser.new do |opts|
  opts.on("-v", "--verbose", "somewhat rather extraneously wordful output") do
    verbose = true
  end
  opts.on("--csv FILENAME", "Append results to file in CSV format") do |f|
    save_csv = f
  end
  opts.on("--csv-columns col1,col2,...", "csv columns list") do |f|
    csv_columns = f.split(/\W+/).map(&:to_sym)
  end
  opts.on("-t", "--time TIME", "Time to run benchmark") do |v|
    init_args[:time] = v
  end
  opts.on("-r", "--msgrate NUMBER", "Message publishing rate per minute per channel") do |v|
    init_args[:messages_per_channel_per_minute] = v
  end
  opts.on("-p", "--msgpadding NUMBER", "Message padding, in bytes") do |v|
    init_args[:message_padding_bytes] = v
  end
  opts.on("-c", "--channels NUMBER", "Number of channels") do |v|
    init_args[:channels] = v
  end
  opts.on("-s", "--subscribers NUMBER", "Subscribers per channel") do |v|
    init_args[:subscribers_per_channel] = v
  end
end
opt_parser.banner="Usage: nchan-benchmark [options] url1 url2 url3..."
opt_parser.parse!

urls = []
urls += ARGV
begin
  urls += STDIN.read_nonblock(100000).split /\s*\n+\s*/
rescue IO::WaitReadable
rescue EOFError
end

urls.uniq!

benchan = NchanTools::Benchmark.new urls, init_args
benchan.run
benchan.results
benchan.append_csv_file(save_csv, csv_columns) if save_csv

