class By2::Options

Constants

OptionsError

Public Class Methods

parse(argv) click to toggle source
# File lib/by2/options.rb, line 5
def self.parse(argv)
  options = { start_date: 2.weeks.ago }
  req_options = {}

  opts = OptionParser.new do |x|
    x.banner = "Usage: by2 [options]"

    x.separator ""
    x.separator "Required options (at least one is required):"

    x.on("-i IP", String, "source or destination ip w/optional port") do |ip|
      req_options[:ip], req_options[:port] = ip.split(":")
    end

    x.on("-s SRC_IP", String, "source ip w/optional port") do |ip|
      req_options[:src_ip], req_options[:src_port] = ip.split(":")
    end

    x.on("-d DST_IP", String, "destination ip w/optional port") do |ip|
      req_options[:dst_ip], req_options[:dst_port] = ip.split(":")
    end

    x.on("-m DUMP_STR", String, "dump string: \"src_ip:src_port -> dst_ip:dst_port\"") do |ips|
      src_ip, dst_ip = ips.split("->")
      req_options[:src_ip], req_options[:src_port] = src_ip.strip.split(":")
      req_options[:dst_ip], req_options[:dst_port] = dst_ip.strip.split(":")
    end

    x.on("-t DATE", String, "date (yyyy-mm-dd)") do |date|
      if date.include?(":")
        req_options[:start_date], req_options[:end_date] = date.split(":")
      else
        req_options[:date] = date
        options.delete(:start_date)
      end
    end


    x.separator ""
    x.separator "Additional options:"

    x.on("-l LIMIT", Integer, "limit number of returned records") do |l|
      options[:limit] = l
    end

    x.on("-D", TrueClass, "debug flag") do
      options[:debug] = true
    end

    x.on("-C", TrueClass, "only print number of records found") do
      options[:count] = true
    end

    x.on("-h", "Show this message") do
      $stdout.puts(opts); exit
    end

    x.on("-H", "Show man page") do
      $stdout.puts(File.read("#{::By2.root}/man/by2.1.txt")); exit
    end
  end

  opts.parse!(argv)

  raise OptionsError if req_options.empty?

  options.merge(req_options)
rescue OptionParser::ParseError, OptionsError => err
  raise OptionsError.new(opts) if err.is_a?(OptionsError)
  raise OptionsError.new(err)
end