#
# Cookbook Name:: kosmos-nginx
# Recipe:: default
#
# The MIT License (MIT)
#
# Copyright:: 2019, Kosmos Developers
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

node.override['nginx']['default_site_enabled'] = false
node.override['nginx']['server_tokens']        = 'off'
node.override['nginx']['log_formats']['json']  = <<-EOF
'{"ip":"$remote_addr",'
'"time":"$time_local",'
'"host":"$host",'
'"method":"$request_method",'
'"uri":"$uri",'
'"status":$status,'
'"size":$body_bytes_sent,'
'"referer":"$http_referer",'
'"upstream_addr":"$upstream_addr",'
'"upstream_response_time":"$upstream_response_time",'
'"ua":"$http_user_agent"}'
EOF

node.override['nginx']['repo_source'] = 'nginx' # Install from official repo
node.override['nginx']['upstream_repository'] = "http://nginx.org/packages/mainline/#{node['platform']}"
include_recipe 'nginx'

# Override the nginx package resource to set a specific version, allowing
# to upgrade it
edit_resource!(:package, 'nginx') do
  version "1.19.1-1~#{node['lsb']['codename']}"
  notifies :reload, 'ohai[reload_nginx]', :immediately
end

# Generate Strong Diffie-Hellman Group (increases security)
# https://weakdh.org/sysadmin.html
openssl_dhparam "/etc/ssl/private/dhparams.pem" do
  key_length 2048
  mode 0600
  owner 'www-data'
end

cookbook_file "#{node['nginx']['dir']}/conf.d/tls_config.conf" do
  source 'nginx_tls_config.conf'
  owner  'root'
  group  'root'
  mode   '0644'
  notifies :restart, 'service[nginx]'
end

directory node["nginx"]["user_home"] do
  owner node["nginx"]["user"]
  group node["nginx"]["group"]
  action :create
  recursive true
end

# Maintenance page, to be copied or served when putting things in maintenance
# mode
cookbook_file "#{node["nginx"]["user_home"]}/maintenance.html" do
  source "maintenance.html"
  owner node['nginx']['user']
  group node['nginx']['group']
  mode "0640"
end

unless node.chef_environment == "development"
  include_recipe "kosmos-nginx::firewall"
end
