resource "kubernetes_secret" "getmail_config" {
  metadata {
    name      = "getmail-config"
    namespace = kubernetes_namespace.mail.metadata[0].name
  }

  data = local.getmail_config
  type = "Opaque"
}

resource "kubernetes_cron_job_v1" "fetch_emails" {
  metadata {
    namespace = kubernetes_namespace.mail.metadata[0].name
    name      = "fetch-emails"
  }

  spec {
    schedule = var.fetch_emails_schedule

    job_template {
      metadata {
        name = "fetch-emails"
      }
      spec {
        backoff_limit           = 1
        parallelism             = 1
        completions             = 1
        active_deadline_seconds = 300

        template {
          metadata {
            labels = {
              app = "fetch-emails"
            }
          }

          spec {
            container {
              name  = "getmail"
              image = "a13labs/getmail6:${var.getmail_tag}"
              args  = concat(["--getmaildir", "/var/getmail"], flatten([for job in local.getmail_jobs : ["-r", "/getmail/getmailrc_${job.name}"]]))

              volume_mount {
                name       = "getmail-config"
                mount_path = "/getmail"
                read_only  = true
              }

              security_context {
                run_as_user  = 1000
                run_as_group = 1000
              }

              volume_mount {
                name       = "getmail-cache"
                mount_path = "/var/getmail"
              }
            }

            restart_policy = "Never"

            volume {
              name = "getmail-config"
              secret {
                secret_name = kubernetes_secret.getmail_config.metadata[0].name
                dynamic "items" {
                  for_each = local.getmail_jobs
                  content {
                    key  = "getmailrc_${items.value.name}"
                    path = "getmailrc_${items.value.name}"
                  }

                }
              }
            }

            volume {
              name = "getmail-cache"
              host_path {
                path = local.getmail_path
              }
            }
          }
        }
      }
    }
  }
}
