resource "random_password" "minio_access_key" {
  length  = 20
  special = false
}

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

resource "helm_release" "minio" {
  name             = "minio"
  repository       = "oci://registry-1.docker.io/bitnamicharts"
  chart            = "minio"
  namespace        = var.namespace
  create_namespace = true
  version          = "16.0.0"
  wait             = true
  wait_for_jobs    = true

  set_sensitive = [{
      name  = "auth.rootUser"
      value = random_password.minio_access_key.result
    },
    {
      name  = "auth.rootPassword"
      value = random_password.minio_secret_key.result
    }]

  set = [{
    name  = "mode"
    value = var.mode
  },

  {
    name  = "resourcesPreset"
    value = "nano"
  },

  {
    name  = "statefulset.replicaCount"
    value = var.replicas
  },

  {
    name  = "statefulset.drivesPerNode"
    value = var.replicas < 4 ? 2 : 1
  },

  {
    name  = "persistence.size"
    value = var.storageSize
  }]

  values = [
    templatefile("${path.module}/values.yaml.tftpl", {
      service_uri       = local.service_uri,
      admin_service_uri = local.admin_service_uri,
      admin             = var.admin,
      tls               = var.mode == "distributed" ? false : var.tls
      ingressClass      = var.ingressClass
      displayOnHomepage = var.displayOnHomepage
    })
  ]
}

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

output "access_key" {
  value     = random_password.minio_access_key.result
  sensitive = true
}

output "secret_key" {
  value     = random_password.minio_secret_key.result
  sensitive = true
}
