resource "kubernetes_config_map" "stunnel_dovecot" {
  metadata {
    name      = "stunnel-dovecot"
    namespace = kubernetes_namespace.mail.metadata[0].name
  }
  data = {
    "stunnel.conf" = local.dovecot_stunnel_config
  }
}

resource "kubernetes_config_map" "stunnel_postfix" {
  metadata {
    name      = "stunnel-postfix"
    namespace = kubernetes_namespace.mail.metadata[0].name
  }
  data = {
    "stunnel.conf" = local.postfix_stunnel_config
  }
}

resource "kubernetes_manifest" "stunnel_cert" {
  manifest = {
    apiVersion = "cert-manager.io/v1"
    kind       = "Certificate"
    metadata = {
      name      = "stunnel-cert"
      namespace = kubernetes_namespace.mail.metadata[0].name
    }
    spec = {
      secretName = "stunnel-cert"
      issuerRef = {
        name = var.issuer
        kind = "ClusterIssuer"
      }
      commonName = "${kubernetes_service.dovecot_auth.metadata[0].name}.${kubernetes_namespace.mail.metadata[0].name}.svc.cluster.local"
      dnsNames   = ["${kubernetes_service.dovecot_auth.metadata[0].name}.${kubernetes_namespace.mail.metadata[0].name}.svc.cluster.local"]
    }
  }
}

resource "kubernetes_config_map" "ca_pem" {
  metadata {
    name      = "ca-pem"
    namespace = kubernetes_namespace.mail.metadata[0].name
  }
  data = {
    "ca.pem" = var.ca_pem
  }
}
