# Render a kubeconfig into the working dir. The `exec` block delegates
# auth to `gke-gcloud-auth-plugin`, which is the supported way to talk to
# GKE after kubectl 1.26+. Users must install it once:
#
#   gcloud components install gke-gcloud-auth-plugin
#
# Like the EKS kubeconfig, this carries no long-lived secrets — the plugin
# refreshes tokens from the user's gcloud auth state on every call.

locals {
  kubeconfig_yaml = yamlencode({
    apiVersion      = "v1"
    kind            = "Config"
    current-context = "aries-${local.cluster_name}"
    clusters = [{
      name = "aries-${local.cluster_name}"
      cluster = {
        server                       = "https://${google_container_cluster.main.endpoint}"
        "certificate-authority-data" = google_container_cluster.main.master_auth[0].cluster_ca_certificate
      }
    }]
    contexts = [{
      name = "aries-${local.cluster_name}"
      context = {
        cluster = "aries-${local.cluster_name}"
        user    = "aries-${local.cluster_name}"
      }
    }]
    users = [{
      name = "aries-${local.cluster_name}"
      user = {
        exec = {
          apiVersion         = "client.authentication.k8s.io/v1beta1"
          command            = "gke-gcloud-auth-plugin"
          provideClusterInfo = true
        }
      }
    }]
  })
}

resource "local_sensitive_file" "kubeconfig" {
  filename             = "${path.cwd}/kubeconfig"
  content              = local.kubeconfig_yaml
  file_permission      = "0600"
  directory_permission = "0700"
}
