#!/usr/bin/env ruby

require '../cvrf/microsoft_cvrf_client.rb'
require 'optparse'
require 'json'

def export_to_json(bulletin_vulns, filepath)
  File.write(filepath, bulletin_vulns)
end

def do_export(bulletin_vulns, bulletin_id)
  filename = "./data/exploited_cves_for_msft_#{bulletin_id}.json"
  export_to_json(bulletin_vulns, filename)
  puts "----" * 12 
  puts "Succesfully Exported to #{filename}:"
  puts "----" * 12 
  puts bulletin_vulns 
  puts "----" * 12 
end

@options = {}

OptionParser.new do |opts|
  opts.on("-id", "--id", "Bulletin ID") do |id|
    @options[:id] = id
  end
  opts.on("--export") do |export|
    @options[:export] =  export
  end
  opts.on("--export-all") do |export_all|
    @options[:export_all] = export_all 
  end
end.parse!

api_client = MicrosoftCvrfClient.new

if (@options[:id] && !@options[:export] && !@options[:export_all])
  exploited_vulns_for_bulletin = api_client.exploited_vulns_only(@options[:id])
  pretty_vulns = JSON.pretty_generate(exploited_vulns_for_bulletin)
  puts "----" * 12 
  puts pretty_vulns
  puts "----" * 12 
elsif (@options[:id] && @options[:export])
  exploited_vulns_for_bulletin = api_client.exploited_vulns_only(@options[:id])
  pretty_vulns = JSON.pretty_generate(exploited_vulns_for_bulletin)
  do_export(pretty_vulns, @options[:id])
elsif (@options[:export_all] && !@options[:id] && !@options[:export])
  puts "Exporting All Bulletin Data:"
  api_client.ids.each do |bulletin_id|
    puts "----" * 12
    puts "Now exporting #{bulletin_id}"
    puts "----" * 12
    # remove these in the next 3 months or put in something that acts based on
    # Date.today.year
    case bulletin_id
    when '2022-Oct'
      next
    when '2022-Nov'
      next
    when '2022-Dec'
      next
    end
    vulns = api_client.exploited_vulns_only(bulletin_id)
    pretty_vulns = JSON.pretty_generate(vulns)
    do_export(pretty_vulns, bulletin_id)
  end
end

puts @options