# Render a standard EKS kubeconfig into the working dir. The `exec` block
# delegates auth to the user's local `aws` CLI (`aws eks get-token`), so
# the kubeconfig itself carries no long-lived secrets — perfect for
# checking in to ~/.aries/cluster/<name>/ alongside cluster.yaml.

locals {
  kubeconfig_yaml = yamlencode({
    apiVersion      = "v1"
    kind            = "Config"
    current-context = "aries-${local.cluster_name}"
    clusters = [{
      name = aws_eks_cluster.main.arn
      cluster = {
        server                       = aws_eks_cluster.main.endpoint
        "certificate-authority-data" = aws_eks_cluster.main.certificate_authority[0].data
      }
    }]
    contexts = [{
      name = "aries-${local.cluster_name}"
      context = {
        cluster = aws_eks_cluster.main.arn
        user    = aws_eks_cluster.main.arn
      }
    }]
    users = [{
      name = aws_eks_cluster.main.arn
      user = {
        exec = {
          apiVersion = "client.authentication.k8s.io/v1beta1"
          command    = "aws"
          args = [
            "--region", var.region,
            "--profile", var.aws_profile,
            "eks", "get-token",
            "--cluster-name", local.cluster_name,
            "--output", "json",
          ]
        }
      }
    }]
  })
}

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