apiVersion: v1
kind: ConfigMap
metadata:
  name: setup-kubeconfig
data:
  prepare_kubeconfig.sh: |
    #!/bin/bash
    SERVICE_ACCOUNT={{ .Values.serviceAccount.name }}
    USER_TOKEN_NAME=$(kubectl -n {{ .Release.Namespace }} get serviceaccount ${SERVICE_ACCOUNT} -o=jsonpath='{.secrets[0].name}')
    USER_TOKEN_VALUE=$(kubectl -n {{ .Release.Namespace }} get secret/${USER_TOKEN_NAME} -o=go-template='{{ "{{.data.token}}" }}' | base64 --decode)
    # CURRENT_CONTEXT=$(kubectl config current-context)
    CURRENT_CONTEXT=$KUBE_CURRENT_CONTEXT
    CLUSTER_CA=`kubectl get secret/$USER_TOKEN_NAME -n {{ .Release.Namespace }} -o jsonpath='{.data.ca\.crt}'`
    CLUSTER_SERVER={{ .Values.knoc.k8sApiServer }}
    echo "
    apiVersion: v1
    kind: Config
    current-context: ${CURRENT_CONTEXT}
    contexts:
    - name: ${CURRENT_CONTEXT}
      context:
        cluster: ${CURRENT_CONTEXT}
        user: default
        namespace: {{ .Release.Namespace }}
    clusters:
    - name: ${CURRENT_CONTEXT}
      cluster:
        certificate-authority-data: ${CLUSTER_CA}
        server: ${CLUSTER_SERVER}
    users:
    - name: default
      user:
        token: ${USER_TOKEN_VALUE}
    "