{{- $cozyConfig := lookup "v1" "ConfigMap" "cozy-system" "cozystack" }}
{{- $host := index $cozyConfig.data "root-host" }}
{{- $k8sClientSecret := lookup "v1" "Secret" "cozy-keycloak" "k8s-client" }}

{{- if $k8sClientSecret }}
{{- $apiServerEndpoint := index $cozyConfig.data "api-server-endpoint" }}
{{- $managementKubeconfigEndpoint := default "" (get $cozyConfig.data "management-kubeconfig-endpoint") }}
{{- if and $managementKubeconfigEndpoint (ne $managementKubeconfigEndpoint "") }}
{{- $apiServerEndpoint = $managementKubeconfigEndpoint }}
{{- end }}
{{- $k8sClient := index $k8sClientSecret.data "client-secret-key" | b64dec }}
{{- $rootSaConfigMap := lookup "v1" "ConfigMap" "kube-system" "kube-root-ca.crt" }}
{{- $k8sCa := index $rootSaConfigMap.data "ca.crt" | b64enc }}

{{- if .Capabilities.APIVersions.Has "helm.toolkit.fluxcd.io/v2" }}
{{- $tenantRoot := lookup "helm.toolkit.fluxcd.io/v2" "HelmRelease" "tenant-root" "tenant-root" }}
{{- if and $tenantRoot $tenantRoot.spec $tenantRoot.spec.values $tenantRoot.spec.values.host }}
{{- $host = $tenantRoot.spec.values.host }}
{{- end }}
{{- end }}
---
apiVersion: v1
kind: Secret
metadata:
  name: kubeconfig-{{ .Release.Namespace }}
stringData:
  kubeconfig: |
    apiVersion: v1
    clusters:
    - cluster:
        server: {{ $apiServerEndpoint }}
        certificate-authority-data: {{ $k8sCa }}
      name: cluster
    contexts:
    - context:
        cluster: cluster
        namespace: {{ .Release.Namespace }}
        user: keycloak
      name: {{ .Release.Namespace }}
    current-context: {{ .Release.Namespace }}
    users:
    - name: keycloak
      user:
        exec:
          apiVersion: client.authentication.k8s.io/v1beta1
          args:
          - oidc-login
          - get-token
          - --oidc-issuer-url=https://keycloak.{{ $host }}/realms/cozy
          - --oidc-client-id=kubernetes
          - --oidc-client-secret={{ $k8sClient }}
          - --skip-open-browser
          command: kubectl
{{- end }}
