locals {
  persistent_folder = var.persistent_folder
  mail_path         = "${local.persistent_folder}/mail"
  mailboxes_path    = "${local.mail_path}/mailboxes"
  getmail_path      = "${local.mail_path}/getmail"
  postfix_path      = "${local.mail_path}/postfix"

  stunnel_tag = "latest"

  getmail_jobs = flatten([
    for account in var.email_accounts : [
      for mailbox in account.mailboxes : {
        name         = "${account.recipient}-${mailbox}"
        recipient    = "${account.recipient}+${mailbox}"
        domain       = account.domain
        server       = account.receive.server
        port         = account.receive.port
        username     = account.username
        password     = account.password
        mailbox      = mailbox
        delete_after = coalesce(account.delete_after, 30)
      }
    ]
  ])

  postfix_env_vars = {
    # Email configuration
    SMTP_HOST            = var.relay_smtp_host
    SMTP_PORT            = var.relay_smtp_port
    MY_PRIMARY_DOMAIN    = var.primary_domain
    MY_DESTINATION       = join(",", [for account in var.email_accounts : account.domain])
    MY_NETWORKS          = "127.0.0.0/8"
    MAILNAME             = "smtp.${var.primary_domain}"
    DOVECOT_LMTP_ADDRESS = "dovecot-lmtp.mail.svc.cluster.local"
    DOVECOT_LMTP_PORT    = 31024
    LOG_TO_STDOUT        = 0
  }

  password_hashes = {
    for account in var.email_accounts : account.username => data.external.password_hasher[account.username].result.hex_encoded_bcrypt_hash
  }

  postfix_secrets = {
    SMTP_USER = {
      key  = "username"
      name = kubernetes_secret.relay_mail_credentials.metadata[0].name
    }

    SMTP_PASSWORD = {
      key  = "password"
      name = kubernetes_secret.relay_mail_credentials.metadata[0].name
    }
  }


  getmail_config = { for job in local.getmail_jobs : "getmailrc_${job.name}" =>

    templatefile("${path.module}/resources/getmail/getmailrc.tpl", {
      recipient            = job.recipient
      domain               = job.domain
      server               = job.server
      port                 = job.port
      username             = job.username
      password             = job.password
      mailbox              = job.mailbox
      delete_after         = job.delete_after
      dovecot_lmtp_address = "dovecot-lmtp.mail.svc.cluster.local"
      dovecot_lmtp_port    = 31024
    })
  }

  postfix_run_config = file("${path.module}/resources/postfix/run.config")
  postfix_bcc_map    = join("\n", [for account in var.email_accounts : "/([^@]+)@${replace(account.domain, ".", "\\.")}/ $${1}+Sent@${account.domain}"])

  postfix_run_config_checksum = sha256(local.postfix_run_config)
  postfix_bcc_map_checksum    = sha256(local.postfix_bcc_map)

  dovecot_config = file("${path.module}/resources/dovecot/dovecot.conf")
  dovecot_users  = join("\n", [for account in var.email_accounts : "${account.username}:{BLF-CRYPT.HEX}${local.password_hashes[account.username]}:1000:1000::/var/mail/${account.username}::"])
  dovecot_sieve  = file("${path.module}/resources/dovecot/sieve")

  dovecot_config_checksum = sha256(local.dovecot_config)
  dovecot_users_checksum  = sha256(local.dovecot_users)
  dovecot_sieve_checksum  = sha256(local.dovecot_sieve)

  dovecot_stunnel_config          = file("${path.module}/resources/dovecot/stunnel.conf")
  dovecot_stunnel_config_checksum = sha256(local.dovecot_stunnel_config)

  postfix_stunnel_config          = file("${path.module}/resources/postfix/stunnel.conf")
  postfix_stunnel_config_checksum = sha256(local.postfix_stunnel_config)
}

data "external" "password_hasher" {
  for_each = { for account in var.email_accounts : account.username => account }
  program  = ["python3", "${path.module}/lib/bcrypt_hash.py"]

  query = {
    password = each.value.password
    cost     = "10"
  }
}
