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