# frozen_string_literal: true

require 'aws-sdk-acm'
require 'aws-sdk-ec2'
require 'set'
require 'thor'

require 'pain/models'
require 'pain/models/acm_certificate'


module Pain
  class CLI < Thor
    def self.exit_on_failure?
      true
    end

    desc 'discover', 'Discover ACM certificates '

    def discover

      profiles = ['cpe-tools', 'cpe-master', 'twilight-shadow', 'twilight-test', 'twilight', 'cpe-tools-shadow', 'cpe-benchmarking', 'twitch-web-aws', 'mobile-upsell-prod', 'mobile-upsell-dev', 'curse']

      profiles.each do |profile|
        ec2 = Aws::EC2::Client.new region: 'us-west-2', profile: profile

        ec2.describe_regions.regions.collect(&:region_name).each do |region|
          puts "#{profile}: #{region}"
          acm = Aws::ACM::Client.new region: region, profile: profile

          acm.list_certificates.certificate_summary_list.each do |summary|
            cert = acm.describe_certificate(certificate_arn: summary.certificate_arn).certificate

            ACMCertificate.update_or_create arn: cert.certificate_arn do |obj|
              obj.profile = profile
              obj.region = region

              obj.domain_name = cert.domain_name
              obj.alternate_names = cert.subject_alternative_names.join('|')

              obj.validation_methods = cert.domain_validation_options.collect(&:validation_method).collect(&:downcase).to_set.to_a.join('|')
              obj.validation_emails = cert.domain_validation_options.collect(&:validation_emails).flatten.compact.to_set.to_a.join('|')

              obj.not_before = cert.not_before
              obj.not_after = cert.not_after

              obj.status = cert.status
              obj.renewal_eligibility = cert.renewal_eligibility
              obj.in_use_by = cert.in_use_by.count
            end
          end
        end
      end
    end
  end
end
