resource "kubernetes_namespace" "postgresql" {
  count = var.enabled ? 1 : 0

  metadata {
    name = var.namespace
  }

  lifecycle {
    ignore_changes = [metadata]
  }
}

resource "random_password" "postgresql_user_password" {
  length           = 40
  special          = true
  override_special = "!#$%&*()-_=+[]{}<>:?"
  min_special      = 2
  min_upper        = 2
  min_lower        = 2
  min_numeric      = 2
}

resource "random_password" "postgresql_root_password" {
  length           = 40
  special          = true
  override_special = "!#$%&*()-_=+[]{}<>:?"
  min_special      = 2
  min_upper        = 2
  min_lower        = 2
  min_numeric      = 2
}

resource "kubernetes_secret" "postgresql_auth" {
  count = var.enabled ? 1 : 0
  type  = "generic"
  depends_on = [var.wait_on]
  metadata {
    name      = "postgresql-auth"
    namespace = kubernetes_namespace.postgresql[count.index].metadata.0.name
  }

  data = {
    password     = random_password.postgresql_user_password.result
    rootpassword = random_password.postgresql_root_password.result
  }
}

resource "helm_release" "postgresql" {
  count      = var.enabled ? 1 : 0
  depends_on = [var.wait_on, kubernetes_secret.postgresql_auth]
  name       = "postgresql"
  repository = "https://charts.bitnami.com/bitnami"
  chart      = "postgresql"
  namespace  = kubernetes_namespace.postgresql[count.index].metadata.0.name
  version    = "16.0.5"
  wait       = true

  values = [
    templatefile("${path.module}/values.yaml", { username = var.username })
  ]
}

output "installed" {
  value = true
  depends_on = [helm_release.postgresql]
}

output "password" {
  value     = random_password.postgresql_user_password.result
  sensitive = true
}

output "root_password" {
  value     = random_password.postgresql_root_password.result
  sensitive = true
}
