class SiteCert
  include Mongoid::Document
  include Mongoid::Timestamps
  mount_uploader :cert_file, AssetUploader #Public key
  mount_uploader :ca_bundle, AssetUploader
  mount_uploader :private_key, AssetUploader
  field :is_certbot, type: Boolean ,default: false
  field :is_valid , type: Boolean ,default: false
  field :domain_names , type: Array ,default: []
  field :source_paths , type: Array ,default: []
  field :start_date , type: DateTime
  field :end_date , type: DateTime
  field :invalid_message, type: String
  has_many :site_constructs, :autosave => true
  after_save :change_data
  def upload_date
  	self.created_at.strftime("%Y/%m/%d %H:%M") rescue ""
  end
  def display_domain_names
  	self.domain_names.join("<br>").html_safe rescue ""
  end
  def generate_file_link(field_name)
  	f = self.send(field_name)
  	file_name = self[field_name]
  	"<a href=\"#{f.url}\" title=\"#{file_name}\">#{file_name}</a>".html_safe
  end
  def display_start_date
    self.start_date.strftime("%Y-%m-%d") rescue ""
  end
  def display_end_date
    self.end_date.strftime("%Y-%m-%d") rescue ""
  end
  def change_data
    if !@skip_callback
      org_cert_file_name = self.cert_file.file.file.to_s
      cert_file_name = org_cert_file_name.sub(/.cer$/, '.crt')
      if org_cert_file_name != cert_file_name
        if File.open(org_cert_file_name, 'r').read().match(/\A\s*---/)
          new_sf = CarrierWave::SanitizedFile.new(self.cert_file.file.move_to(cert_file_name))
        else
          `openssl x509 --inform DER -in #{org_cert_file_name} --out #{cert_file_name}`
          new_sf = CarrierWave::SanitizedFile.new(cert_file_name)
        end
        self.cert_file.cache!(new_sf)
      end
    	cert_file_md5 = `openssl x509 -noout -modulus -in #{cert_file_name} | openssl md5`
    	private_key_md5 = `openssl rsa -noout -modulus -in #{self.private_key.file.file} | openssl md5`
    	is_valid = (cert_file_md5 == private_key_md5)
      domain_names = `openssl x509 -text <  #{cert_file_name} | grep 'DNS:' | sed 's/\s*DNS:\([a-z0-9.\-]*\)[,\s]\?/\1 /g'`.split('DNS:').map{|s| s.sub(',','').strip}.select{|s| s.present?} rescue []
    	if domain_names.length == 0
        domain_names = [`openssl x509 -text <  #{cert_file_name} | grep 'Subject' | grep 'CN =' | grep 'Subject' | grep 'CN =' |sed 's/\s*Subject: //g'`[0...-1].split(/, | = /).each_slice(2).to_h['CN']] rescue []
    	end
      sign_algo_valid = `openssl x509 -text <  #{cert_file_name} | grep 'Signature Algorithm: sha1'`[0...-1].blank? rescue false
      invalid_messages = []
      if !is_valid
        invalid_messages << 'cert and key not match'
      end
      if !sign_algo_valid
        invalid_messages << 'Signature Algorithm cannot use sha1, please use sha256'
      end
      if domain_names.blank?
        invalid_messages << 'Domain Names(alt_names) is empty.'
      end
      self.invalid_message = invalid_messages.join(', ')
      if is_valid
        is_valid = sign_algo_valid
      end
      if domain_names.blank?
        self.is_valid = false
      else
        start_date_text = `openssl x509 -text <  #{cert_file_name} -startdate -noout`.split('=').last.strip
        end_date_text = `openssl x509 -text <  #{cert_file_name} -enddate -noout`.split('=').last.strip
        self.start_date = DateTime.parse(start_date_text) rescue nil
        self.end_date = DateTime.parse(end_date_text) rescue nil
        self.is_valid = is_valid
        self.domain_names = domain_names
      end
      @skip_callback = true
      self.save(:validate=>false)
      @skip_callback = false
    	false
    end
  end
  def valid_domain_names(site_names)
    site_names = site_names.split(" ").map{|s| s.strip}
    valid_site_names = []
    self.domain_names.each do |d|
      regx = ::Regexp.new("\\A"+d.gsub('.',"\\.").gsub('*','[^\\.]+').sub(',','').strip)
      valid_site_names += site_names.select{|s| !(s.match(regx).nil?)}
    end
    return valid_site_names
  end
end