{ config, lib, ... }:
let
  cfg = config.khscodes.security.acme;
  vaultAgentCredentialsFile = "/var/lib/vault-agent/acme/cloudflare-api-token";
  cloudflareSecret = "opentofu/data/cloudflare";
  acmeServicesToRestart = lib.lists.map (a: "acme-${a}.service") (
    lib.attrsets.attrNames config.security.acme.certs
  );
in
{
  options.khscodes.security.acme = {
    enable = lib.mkEnableOption "Enables acme";
    dns01Enabled = lib.mkOption {
      type = lib.types.bool;
      description = "Whether to use DNS01 instead of http-01 challenges. This will make the approle gain policy to retrieve the needed cloudflare secrets to manage dns.";
      default = config.khscodes.infrastructure.khs-openstack-instance.enable;
    };
  };
  config = lib.mkIf cfg.enable {
    security.acme = {
      acceptTerms = true;
      defaults =
        {
          email = "kaare@kaareskovgaard.net";
        }
        // lib.attrsets.optionalAttrs cfg.dns01Enabled {
          dnsProvider = "cloudflare";
          dnsResolver = null;
          credentialsFile = vaultAgentCredentialsFile;
        };
    };
    khscodes.infrastructure.vault-server-approle = lib.mkIf cfg.dns01Enabled {
      enable = true;
      policy = {
        "${cloudflareSecret}" = {
          capabilities = [ "read" ];
        };
      };
    };
    khscodes.services.vault-agent = lib.mkIf (cfg.dns01Enabled && acmeServicesToRestart != [ ]) {
      enable = true;
      templates = [
        {
          contents = ''
            {{- with secret "${cloudflareSecret}" -}}
            CLOUDFLARE_DNS_API_TOKEN={{ .Data.data.TF_VAR_cloudflare_token }}
            CLOUDFLARE_DNS_EMAIL={{ .Data.data.TF_VAR_cloudflare_email }}
            {{- end -}}
          '';
          destination = vaultAgentCredentialsFile;
          perms = "0600";
          owner = "acme";
          group = "acme";
          restartUnits = acmeServicesToRestart;
        }
      ];
    };
  };
}
