resource_name :nginx_certbot_site
provides :nginx_certbot_site

property :domain, String, name_property: true
# pass it if the site name is not the same as the hostname, for example for the
# different parity services running on different ports
property :site, String

action :create do
  return if node.chef_environment == "development"

  domain = new_resource.domain
  site = new_resource.site || domain
  root_directory = "/var/www/#{domain}"

  directory "#{root_directory}/.well-known/acme-challenge" do
    owner node["nginx"]["user"]
    group node["nginx"]["group"]
    action :create
    recursive true
  end

  template "#{node['nginx']['dir']}/sites-available/#{domain}_certbot" do
    source "nginx_conf_certbot.erb"
    cookbook "kosmos-nginx"
    owner node["nginx"]["user"]
    mode 0640
    variables server_name:    domain,
              root_directory: root_directory

    notifies :reload, 'service[nginx]', :delayed
  end

  nginx_site "#{domain}_certbot" do
    action :enable
    notifies :reload, 'service[nginx]', :immediately
  end

  include_recipe "kosmos-base::letsencrypt"

  certbot_bin = node[:platform_version].to_f < 20.04 ? "/usr/bin/certbot" : "/snap/bin/certbot"

  # Generate a Let's Encrypt cert (only if the nginx vhost exists and no cert
  # has been generated before. The renew cron will take care of renewing
  execute "letsencrypt cert for #{domain}" do
    command "#{certbot_bin} certonly --webroot --agree-tos --email ops@kosmos.org --webroot-path #{root_directory} -d #{domain} -n"
    only_if do
      ::File.exist?("#{node['nginx']['dir']}/sites-enabled/#{domain}_certbot") &&
        !::File.exist?("/etc/letsencrypt/live/#{domain}/fullchain.pem")
    end
    notifies :create, "template[#{node['nginx']['dir']}/sites-available/#{site}]", :immediately
  end
end
