#!/usr/bin/env ruby -KU
require 'kramdown-rfc/kdrfc-processor'
require 'optparse'

# try to get this from gemspec.
KDRFC_VERSION=Gem.loaded_specs["kramdown-rfc2629"].version rescue "unknown-version"

kdrfc = KramdownRFC::KDRFC.new
kdrfc.options.txt = true             # default

op = OptionParser.new do |opts|
  opts.banner = <<BANNER
Usage: kdrfc [options] file.md|file.xml
Version: #{KDRFC_VERSION}
BANNER
  opts.on("-V", "--version", "Show version and exit") do |v|
    puts "kdrfc, from kramdown-rfc2629 #{KDRFC_VERSION}"
    exit
  end
  opts.on("-H", "--help", "Show option summary and exit") do |v|
    puts opts
    exit
  end
  opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
    kdrfc.options.verbose = v
  end
  opts.on("-r", "--[no-]remote", "Run xml2rfc remotely even if there is a local one") do |v|
    kdrfc.options.remote = v
  end
  opts.on("-x", "--[no-]xml", "Convert to xml only") do |v|
    kdrfc.options.xml_only = v
  end
  opts.on("-p", "--[no-]prep", "Convert xml to prepped xml") do |v|
    kdrfc.options.prep = v
  end
  opts.on("-P", "-f", "--[no-]pdf", "Convert xml to PDF") do |v|
    kdrfc.options.pdf = v
  end
  opts.on("-c", "--[no-]convert", "Convert xml to v3 xml") do |v|
    kdrfc.options.v2v3 = v
  end
  opts.on("-i", "--[no-]idnits", "Run idnits on the resulting text") do |v|
    kdrfc.options.idnits = v
  end
  opts.on("-h", "--[no-]html", "Convert to html as well") do |v|
    kdrfc.options.html = v
  end
  opts.on("-t", "--[no-]txt", "Convert to txt as well (default)") do |v|
    kdrfc.options.txt = v
  end
  opts.on("-n", "Do not convert to txt (--no-txt)") do |v|
    kdrfc.options.txt = !v
  end
  opts.on("-3", "--[no-]v3", "Use RFCXML v3 processing rules") do |v|
    kdrfc.options.v3 = v
  end
  opts.on("-2", "--[no-]v2", "Use RFCXML v2 processing rules") do |v|
    kdrfc.options.v2 = v
  end
  opts.on("-dNN", "--docrev=NN", /[0-9][0-9]/, "Replace -latest by -NN in docname") do |v|
    ENV["KRAMDOWN_RFC_DOCREV"] = v
  end
end
op.parse!


if kdrfc.options.v2 && kdrfc.options.v3
  warn "*** can't have v2 and eat v3 cake"
  kdrfc.options.v2 = false
end

if kdrfc.options.v3.nil? && !kdrfc.options.v2
  if Time.now.to_i >= 1645567342 # Time.parse("2022-02-22T22:02:22Z").to_i
    kdrfc.options.v3 = true           # new default from the above date
  end
end

warn "*** v2 #{kdrfc.options.v2.inspect} v3 #{kdrfc.options.v3.inspect}" if kdrfc.options.verbose

case ARGV.size
when 1
  fn = ARGV[0]
  begin
    kdrfc.process(fn)
  rescue StandardError => e
    warn e.to_s
    exit 1
  end
else
  puts op
  exit 1
end
