# encoding: utf-8
require 'yaml'
require 'octokit'

class CVEEmailPreparerAndGithubIssueNotifier
  def self.notify!(cves, contents)
    write_directory = ENV.fetch('EMAIL_PREPARER_DIR')
    FileUtils.mkdir_p(write_directory)

    email_headers_file_path = File.join(write_directory, 'headers') + '-' + contents[:category]
    email_subject_file_path = File.join(write_directory, 'subject') + '-' + contents[:category]
    email_body_file_path = File.join(write_directory, 'body') + '-' + contents[:category]

    write_email_headers_file(email_headers_file_path)
    write_email_subject_file(cves, email_subject_file_path)
    write_email_body_file(create_github_issues(cves, contents), email_body_file_path, contents)
  end

  private

  def self.create_github_issues(cves, contents)
    Octokit.auto_paginate = true
    Octokit.configure do |c|
      c.login    = ENV.fetch('GITHUB_USERNAME')
      c.password = ENV.fetch('GITHUB_PASSWORD')
    end

    labels = contents[:labels]
    github_repos = ['cloudfoundry/security-notices']
    cve_to_issue_url_map = {}

    cves.each do |cve|
      github_issue_urls = github_repos.map do |repo|
        response = Octokit.create_issue(
          repo,
          cve['title'],
          "```\n#{cve['description']}\n```",
          labels: labels
        )
        response[:html_url]
      end

      cve_to_issue_url_map[cve] = github_issue_urls
    end

    cve_to_issue_url_map
  end

  def self.write_email_headers_file(write_path)
    headers = email_headers
    File.write(write_path, headers)
  end

  def self.write_email_subject_file(cves, write_path)
    subject = email_subject(cves)
    File.write(write_path, subject)
  end

  def self.write_email_body_file(cve_to_github_issues_map, write_path, contents)
    body = ''

    cve_to_github_issues_map.each do |cve, github_issue_url|
      body += formatted_cve(cve, github_issue_url, contents)
    end

    File.write(write_path, body)
  end

  def self.email_headers
    headers = <<-HEADERS
MIME-version: 1.0
Content-Type: text/html; charset="UTF-8"
HEADERS
  end

  def self.email_subject(cves)
    subject = 'New CVEs: ' + cves.map { |cve| cve['title'] }.join(', ')
  end

  def self.formatted_cve(cve, github_issue_urls, contents)
    case contents[:category]
    when 'cflinuxfs2-related'
      rootfs_presence = '<h2><b>Present</b> in rootfs</h2>'
    when 'cflinuxfs2-unrelated'
      rootfs_presence = '<h2><b>Not present</b> in rootfs</h2>'
    else
      rootfs_presence = ''
    end

    github_issue_elements = github_issue_urls.reduce('') do |html, issue_url|
      html += "<a href='#{issue_url}'>#{issue_url}</a>\n"
    end

    "<h1>#{cve['title']}</h1>\n#{rootfs_presence}\n#{github_issue_elements}\n#{cve['raw_description']}\n"
  end
end
