locals {
  persistent_folder = var.persistent_folder

  database_credentials = {
    MYSQL_USER = {
      key  = "username"
      name = var.app_config.db_user
    }

    MYSQL_PASSWORD = {
      key  = "password"
      name = var.app_config.db_password
    }
  }

  nextcloud_env_vars = merge({
    # Database configuration
    MYSQL_DATABASE = var.app_config.db_name
    MYSQL_HOST     = var.app_config.db_host

    # Email configuration
    SMTP_HOST         = var.app_config.smtp_host
    SMTP_SECURE       = var.app_config.smtp_secure
    SMTP_PORT         = var.app_config.smtp_port
    MAIL_FROM_ADDRESS = var.app_config.mail_from
    MAIL_DOMAIN       = var.app_config.mail_domain
    SMTP_AUTHTYPE     = "PLAIN"

    # Redis configuration
    REDIS_HOST = "redis"

    # General
    NEXTCLOUD_TRUSTED_DOMAINS = var.fqdn
    TRUSTED_PROXIES           = join(" ", ["10.1.0.0/16"])
    OVERWRITEHOST             = var.fqdn
    OVERWRITEPROTOCOL         = "https"
    OVERWRITECLIURL           = "https://${var.fqdn}"

    # PHP
    PHP_MEMORY_LIMIT = "512M"
  }, var.db_credentials_are_secrets ? {} : local.database_credentials)

  nextcloud_secrets = merge({

    SMTP_NAME = {
      key  = "username"
      name = kubernetes_secret.nextcloud_mail_credentials.metadata[0].name
    }

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

    NEXTCLOUD_ADMIN_USER = {
      key  = "username"
      name = kubernetes_secret.nextcloud_admin_credentials.metadata[0].name
    }

    NEXTCLOUD_ADMIN_PASSWORD = {
      key  = "password"
      name = kubernetes_secret.nextcloud_admin_credentials.metadata[0].name
    }
  }, var.db_credentials_are_secrets ? local.database_credentials : {})


  nextcloud_data = "${local.persistent_folder}/nextcloud"

  apache_confs = {
    for f in fileset("${path.module}/resources/apache2/conf-enabled/", "*.conf") :
    "${f}" => file("${path.module}/resources/apache2/conf-enabled//${f}")
  }
  apache_mods_load = {
    for f in fileset("${path.module}/resources/apache2/mods-enabled/", "*.cload") :
    "${f}" => file("${path.module}/resources/apache2/mods-enabled//${f}")
  }
  apache_mods_conf = {
    for f in fileset("${path.module}/resources/apache2/mods-enabled/", "*.conf") :
    "${f}" => file("${path.module}/resources/apache2/mods-enabled//${f}")
  }
  apache_sites = {
    for f in fileset("${path.module}/resources/apache2/sites-enabled/", "*.conf") :
    "${f}" => file("${path.module}/resources/apache2/sites-enabled//${f}")
  }

  apache_confs_checksum     = sha256(jsonencode(local.apache_confs))
  apache_sites_checksum     = sha256(jsonencode(local.apache_sites))
  apache_mods_load_checksum = sha256(jsonencode(local.apache_mods_load))
  apache_mods_conf_checksum = sha256(jsonencode(local.apache_mods_conf))
}
