resource "random_password" "admin_password" {
  length  = 48
  special = true
}

data "kubernetes_secret" "bridge-tls" {
  metadata {
    name      = "bridge-tls"
    namespace = "cert-manager"
  }
}

resource "kubernetes_namespace" "argocd" {
  metadata {
    name = var.namespace
  }

  lifecycle {
    ignore_changes = [metadata]
  }
}

resource "kubernetes_secret" "argocd-tls" {
  metadata {
    name      = "argocd-tls"
    namespace = kubernetes_namespace.argocd.metadata[0].name
  }

  data = data.kubernetes_secret.bridge-tls.data
  type = data.kubernetes_secret.bridge-tls.type
}

resource "helm_release" "argocd" {
  depends_on = [var.wait_on]
  name             = "argocd"
  repository       = "https://charts.bitnami.com/bitnami"
  chart            = "argo-cd"
  namespace        = kubernetes_namespace.argocd.metadata[0].name
  version          = "9.0.29"
  create_namespace = false
  wait             = true
  wait_for_jobs    = true

  set_sensitive = [{
    name  = "config.secret.argocdServerAdminPassword"
    value = random_password.admin_password.result
  }]

  values = [
    templatefile("${path.module}/values.yaml.tftpl", {
      service_uri         = local.service_uri,
      server_dns          = var.server_dns,
      grpc_service_uri    = local.grpc_service_uri,
      redis_index         = var.redis_db_start_index,
      redis_password      = var.redis_password,
      redis_service_uri   = "redis-headless.redis.svc.cluster.local",
      oauth_uri           = var.oauth_uri,
      oauth_issuer        = var.oauth_issuer,
      oauth_client_id     = var.oauth_client_id,
      oauth_client_secret = var.oauth_client_secret,
      oauth_redirect_uri  = var.oauth_redirect_uri,
      tls                 = var.tls,
      ingress_class       = var.ingressClass
    })
  ]
}

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

output "admin_password" {
  value     = random_password.admin_password.result
  sensitive = true
}

output "redis_db_next_start_index" {
  value = var.redis_db_start_index + 1
}
