#
# Cookbook:: irrigate-nginx
# Recipe:: ad_auth
#
# Copyright:: (C) 2017 The Orchard
#

packages = %w(
  pam-devel
  nss_ldap
  unzip
)

packages.each do |name|
  package name
end

cookbook_file '/etc/pam.d/pam_auth_nginx' do
  source 'pam_auth_nginx'
  owner 'root'
  group 'root'
  action :create
end

nslcd_config_location = node['nginx']['nslcd_config']['path']
ad_server = node['nginx']['ad_server']
ad_port = node['nginx']['ad_port']
ad_protocol = node['nginx']['ad_protocol']
ad_search_base = node['nginx']['ad_search_base']
ad_bind_credentials = data_bag_item('secrets', 'ad_kibana_bind_credentials')
ad_bind_dn = ad_bind_credentials['bind_dn'].chomp
ad_bind_password = ad_bind_credentials['bind_password'].chomp
template nslcd_config_location do
  source 'nslcd.conf.erb'
  owner 'root'
  group 'root'
  mode '0600'
  variables(ad_server: ad_server,
            ad_port: ad_port,
            ad_protocol: ad_protocol,
            ad_search_base: ad_search_base,
            ad_bind_dn: ad_bind_dn,
            ad_bind_password: ad_bind_password)
end

service 'nslcd' do
  supports restart: true
  action [:enable, :start]
  subscribes :restart, '[nslcd.conf]', :immediately
end

auth_pam_src_filename = "http_auth_pam_module-v#{node['nginx']['auth_pam']['version']}.zip"
auth_pam_src_filepath = "#{Chef::Config['file_cache_path']}/#{auth_pam_src_filename}"
auth_pam_extract_path = "#{Chef::Config['file_cache_path']}/nginx_auth_pam_module"

remote_file auth_pam_src_filepath do
  source   node['nginx']['auth_pam']['url']
  checksum node['nginx']['auth_pam']['checksum']
end

bash 'extract_auth_pam_module' do
  cwd ::File.dirname(auth_pam_src_filepath)
  code <<-EOH
    unzip #{auth_pam_src_filename} -d #{auth_pam_extract_path}
    mv #{auth_pam_extract_path}/*/* #{auth_pam_extract_path}/
  EOH
  not_if { ::File.exist?(auth_pam_extract_path) }
end

node.default['nginx']['source']['default_configure_flags'] = node.default['nginx']['source']['default_configure_flags'] | ["--add-module=#{auth_pam_extract_path}"]
directory node['nginx']['socketproxy']['root'] do
  action :create
  recursive true
end

include_recipe 'nginx::default'

cookbook_file "#{node['nginx']['dir']}/conf.d/nginx_enable_ldap_auth.conf" do
  source 'nginx_enable_ldap_auth.conf'
  notifies :reload, 'service[nginx]', :delayed
end
