#
# Cookbook Name:: ssl_cert
# Library:: Helper
#
# Copyright 2016, whitestar
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

module SSLCert
  # Helper methods.
  module Helper
    def ssl_cert_pkg
      case node['platform_family']
      when 'debian'
        pkg = 'ssl-cert'
        resources(package: pkg) rescue package pkg do
          action :install
        end
      when 'rhel'
        enable_command = 'update-ca-trust_enable'
        resources(execute: enable_command) rescue execute enable_command do
          user 'root'
          command 'update-ca-trust enable'
          action :run
          only_if { node['platform_version'].to_i == 6 }
          only_if 'update-ca-trust check | grep DISABLED'
        end
      end
    end

    def get_private_key_group
      if node['ssl_cert']['rhel']['key_access_group'].nil? \
        || node['ssl_cert']['rhel']['key_access_group'].empty?
        node.override['ssl_cert']['rhel']['key_access_group'] = 'root'
      end

      node.value_for_platform_family(
        'debian'  => 'ssl-cert',
        'rhel'    => node['ssl_cert']['rhel']['key_access_group'],
        'default' => 'root'
      )
    end

    def get_private_key_mode
      node.value_for_platform_family(
        'debian'  => 0640,
        'rhel'    => 0400,
        'default' => 0400
      )
    end

    def chef_gem_chef_vault
      pkg = 'chef-vault'
      resources(chef_gem: pkg) rescue chef_gem pkg do
        compile_time true if respond_to?(:compile_time)
        clear_sources node['ssl_cert']['chef_gem']['clear_sources']
        source node['ssl_cert']['chef_gem']['source']
        options node['ssl_cert']['chef_gem']['options']
        version node['ssl_cert']['chef-vault']['version']
        action :install
      end
    end

    def vault_item_suffix
      suffix = \
        if !node['ssl_cert']['vault_item_suffix'].nil? && !node['ssl_cert']['vault_item_suffix'].empty?
          node['ssl_cert']['vault_item_suffix']
        else
          ''
        end

      suffix
    end

    def ca_cert_src_path(ca)
      undotted_ca = ca.tr('.', '_')
      node['ssl_cert']["#{undotted_ca}_cert_src_path"]
    end

    def ca_cert_path(ca)
      undotted_ca = ca.tr('.', '_')
      node['ssl_cert']["#{undotted_ca}_cert_path"]
    end

    def ca_certificate(ca)
      ssl_cert_pkg

      chef_gem_chef_vault
      require 'chef-vault'
      cert = ChefVault::Item.load(
        node['ssl_cert']['ca_cert_vault'], "#{ca}#{vault_item_suffix}")
      node['ssl_cert']['ca_cert_vault_item_key'].split('/').each {|elm|
        cert = cert[elm]
      }

      cert_path = ca_cert_src_path(ca)
      #cert_path = ca_cert_path(ca)
      cert_file_name = File.basename(cert_path)
      update_command_name = 'update-ca-certificates'
      update_command = ''

      resources(file: cert_path) rescue file cert_path do
        content cert
        owner 'root'
        group 'root'
        mode 0644
        notifies :run, "execute[#{update_command_name}]", :delayed
      end

      case node['platform_family']
      when 'debian'
        execute "add_ca_cert_entry_#{cert_file_name}" do
          user 'root'
          command "echo #{cert_file_name} >> /etc/ca-certificates.conf"
          action :run
          not_if "cat /etc/ca-certificates.conf | grep #{cert_file_name}"
          notifies :run, "execute[#{update_command_name}]", :delayed
        end

        update_command = 'update-ca-certificates'
      when 'rhel'
        update_command = 'update-ca-trust extract'
      end

      resources(execute: update_command_name) rescue execute update_command_name do
        user 'root'
        command update_command
        action :nothing
      end
    end

    def ca_pubkey_path(ca)
      undotted_ca = ca.tr('.', '_')
      node['ssl_cert']["#{undotted_ca}_pubkey_path"]
    end

    def ca_public_key(ca)
      ssl_cert_pkg

      chef_gem_chef_vault
      require 'chef-vault'
      pubkey = ChefVault::Item.load(
        node['ssl_cert']['ca_pubkey_vault'], "#{ca}#{vault_item_suffix}")
      node['ssl_cert']['ca_pubkey_vault_item_key'].split('/').each {|elm|
        pubkey = pubkey[elm]
      }

      pubkey_path = ca_pubkey_path(ca)
      resources(file: pubkey_path) rescue file pubkey_path do
        content pubkey
        owner 'root'
        group 'root'
        mode 0644
      end
    end

    def ssh_ca_krl_path(ca)
      undotted_ca = ca.tr('.', '_')
      node['ssl_cert']["#{undotted_ca}_krl_path"]
    end

    def ssh_ca_krl(ca)
      ssl_cert_pkg

      chef_gem_chef_vault
      require 'chef-vault'
      krl = ChefVault::Item.load(
        node['ssl_cert']['ssh_ca_krl_vault'], "#{ca}#{vault_item_suffix}")
      node['ssl_cert']['ssh_ca_krl_vault_item_key'].split('/').each {|elm|
        krl = krl[elm]
      }

      krl_path = ssh_ca_krl_path(ca)
      resources(file: krl_path) rescue file krl_path do
        content krl
        owner 'root'
        group 'root'
        mode 0644
      end
    end

    def server_cert_path(cn)
      undotted_cn = cn.tr('.', '_')
      node['ssl_cert']["#{undotted_cn}_cert_path"]
    end

    def server_certificate(cn)
      ssl_cert_pkg

      chef_gem_chef_vault
      require 'chef-vault'
      cert = ChefVault::Item.load(
        node['ssl_cert']['server_cert_vault'], "#{cn}#{vault_item_suffix}")
      node['ssl_cert']['server_cert_vault_item_key'].split('/').each {|elm|
        cert = cert[elm]
      }

      cert_path = server_cert_path(cn)
      resources(file: cert_path) rescue file cert_path do
        content cert
        owner 'root'
        group 'root'
        mode 0644
      end
    end

    def server_key_path(cn)
      undotted_cn = cn.tr('.', '_')
      node['ssl_cert']["#{undotted_cn}_key_path"]
    end

    def server_private_key(cn)
      ssl_cert_pkg

      chef_gem_chef_vault
      require 'chef-vault'
      secret = ChefVault::Item.load(
        node['ssl_cert']['server_key_vault'], "#{cn}#{vault_item_suffix}")
      node['ssl_cert']['server_key_vault_item_key'].split('/').each {|elm|
        secret = secret[elm]
      }

      key_path = server_key_path(cn)
      key_group = get_private_key_group
      resources(group: key_group) rescue group key_group do
        system true
        action :create
      end
      key_mode = get_private_key_mode

      resources(file: key_path) rescue file key_path do
        content secret
        sensitive true
        owner 'root'
        group key_group
        mode key_mode
      end
    end
  end
end
