#
# Cookbook:: kosmos-ejabberd
# Recipe:: upload_service
#

include_recipe "kosmos-nginx::with_perl"

ejabberd_credentials = data_bag_item("credentials", "ejabberd")
uploads_secret = ejabberd_credentials["uploads_secret"]

upload_config = node["kosmos-ejabberd"]["uploads"]
domain = upload_config["domain"]

git "/opt/upload.pm" do
  repository upload_config["upload.pm"]["repo"]
  revision upload_config["upload.pm"]["revision"]
  action :sync
end

directory "/var/www/upload" do
  user node["nginx"]["user"]
  group node["nginx"]["group"]
  mode "0755"
end

ruby_block "configure uploads.pm" do
  block do
    file = Chef::Util::FileEdit.new("/opt/upload.pm/upload.pm")
    file.search_file_replace(%r{it-is-secret}, uploads_secret)
    file.search_file_replace_line(
      %r{my \$uri_prefix_components = 0;},
      'my $uri_prefix_components = 1;'
    )
    file.write_file
  end
end

ruby_block "configure perl module in nginx" do
  block do
    file = Chef::Util::FileEdit.new("/etc/nginx/nginx.conf")
    file.insert_line_after_match(
      %r{types_hash_bucket_size},
      "\n\n  perl_modules /opt/upload.pm;\n  perl_require upload.pm;"
    )
    file.write_file
  end
end

template "#{node["nginx"]["dir"]}/sites-available/#{domain}" do
  source "nginx_conf_upload_service.erb"
  owner node["nginx"]["user"]
  mode 0640
  variables server_name: domain,
            ssl_cert:    "/etc/letsencrypt/live/#{domain}/fullchain.pem",
            ssl_key:     "/etc/letsencrypt/live/#{domain}/privkey.pem",
            max_upload_size_mb: upload_config["max_upload_size_mb"]
  notifies :reload, "service[nginx]", :delayed
end

nginx_site domain do
  action :enable
end

nginx_certbot_site domain
