require 'ox'

class RhelRpmToCve
  # filepath == /path/to/rpm-to-cve.xml
  attr_accessor :filepath, :file, :xml
  
  def initialize(filepath)
    @filepath = filepath
    @file = File.read(filepath)
    @xml = Ox.parse(file)
  end

  def list_pkg_names
    xml.rpms.locate("?/@rpm")
  end

  def pkg_exists?(pkg_name)
    list_pkg_names.include? pkg_name
  end

  def cves_per_pkg_name(pkg_name)
    if pkg_exists? pkg_name
      results = find_pkg(pkg_name).locate('*/cve').map do |r|
        r.text
      end.compact

      { 
        :rhel_package_name => pkg_name,
        :cves => results.map {|cve| cve}
      }
    else
      'Package not found.'
    end
  end

  def find_pkg(pkg_name)
    xml.rpms.locate("rpm[@rpm=#{pkg_name}]").first
  end

  def convert_to_json
    pkgs = list_pkg_names
    pkgs_and_cves = pkgs.map do |pkg_name|
      cves_per_pkg_name(pkg_name)
    end
    pkgs_and_cves.to_json
  end
end