{{- /*
Copyright Broadcom, Inc. All Rights Reserved.
SPDX-License-Identifier: APACHE-2.0
*/}}

{{- if and .Values.auth.enabled (not .Values.auth.existingSecret) .Values.createAdminTokenJob.enabled (ne .Values.objectStore "memory") }}
apiVersion: batch/v1
kind: Job
metadata:
  name: {{ printf "%s-create-admin-token" (include "common.names.fullname" .) | trunc 63 | trimSuffix "-" }}
  namespace: {{ include "common.names.namespace" . | quote }}
  labels: {{- include "common.labels.standard" ( dict "customLabels" .Values.commonLabels "context" $ ) | nindent 4 }}
    app.kubernetes.io/part-of: influxdb
    app.kubernetes.io/component: create-admin-token
  {{- $defaultAnnotations := ternary (dict "helm.sh/hook" "pre-install" "helm.sh/hook-delete-policy" "before-hook-creation,hook-succeeded") (dict) .Values.useHelmHooks }}
  {{- $annotations := include "common.tplvalues.merge" (dict "values" (list .Values.createAdminTokenJob.annotations .Values.commonAnnotations $defaultAnnotations) "context" .) }}
  annotations: {{- include "common.tplvalues.render" (dict "value" $annotations "context" .) | nindent 4 }}
spec:
  backoffLimit: {{ .Values.createAdminTokenJob.backoffLimit }}
  template:
    metadata:
      {{- $podLabels := include "common.tplvalues.merge" ( dict "values" ( list .Values.createAdminTokenJob.podLabels .Values.commonLabels ) "context" . ) }}
      labels: {{- include "common.labels.standard" ( dict "customLabels" $podLabels "context" $ ) | nindent 8 }}
        app.kubernetes.io/part-of: influxdb
        app.kubernetes.io/component: create-admin-token
      {{- if .Values.createAdminTokenJob.podAnnotations }}
      annotations: {{- include "common.tplvalues.render" (dict "value" .Values.createAdminTokenJob.podAnnotations "context" $) | nindent 8 }}
      {{- end }}
    spec:
      {{- include "influxdb.imagePullSecrets" . | nindent 6 }}
      restartPolicy: OnFailure
      automountServiceAccountToken: {{ .Values.createAdminTokenJob.automountServiceAccountToken }}
      serviceAccountName: {{ include "influxdb.createAdminTokenJob.serviceAccountName" . }}
      {{- if .Values.createAdminTokenJob.hostAliases }}
      hostAliases: {{- include "common.tplvalues.render" (dict "value" .Values.createAdminTokenJob.hostAliases "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.createAdminTokenJob.affinity }}
      affinity: {{- include "common.tplvalues.render" (dict "value" .Values.createAdminTokenJob.affinity "context" $) | nindent 8 }}
      {{- else }}
      affinity:
        podAffinity: {{- include "common.affinities.pods" (dict "type" .Values.createAdminTokenJob.podAffinityPreset "component" "create-admin-token" "customLabels" $podLabels "topologyKey" .Values.createAdminTokenJob.topologyKey "context" $) | nindent 10 }}
        podAntiAffinity: {{- include "common.affinities.pods" (dict "type" .Values.createAdminTokenJob.podAntiAffinityPreset "component" "create-admin-token" "customLabels" $podLabels "topologyKey" .Values.createAdminTokenJob.topologyKey "context" $) | nindent 10 }}
        nodeAffinity: {{- include "common.affinities.nodes" (dict "type" .Values.createAdminTokenJob.nodeAffinityPreset.type "key" .Values.createAdminTokenJob.nodeAffinityPreset.key "values" .Values.createAdminTokenJob.nodeAffinityPreset.values) | nindent 10 }}
      {{- end }}
      {{- if .Values.createAdminTokenJob.nodeSelector }}
      nodeSelector: {{- include "common.tplvalues.render" (dict "value" .Values.createAdminTokenJob.nodeSelector "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.createAdminTokenJob.terminationGracePeriodSeconds }}
      terminationGracePeriodSeconds: {{ .Values.createAdminTokenJob.terminationGracePeriodSeconds }}
      {{- end }}
      {{- if .Values.createAdminTokenJob.tolerations }}
      tolerations: {{- include "common.tplvalues.render" (dict "value" .Values.createAdminTokenJob.tolerations "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.createAdminTokenJob.topologySpreadConstraints }}
      topologySpreadConstraints: {{- include "common.tplvalues.render" (dict "value" .Values.createAdminTokenJob.topologySpreadConstraints "context" .) | nindent 8 }}
      {{- end }}
      {{- if .Values.createAdminTokenJob.priorityClassName }}
      priorityClassName: {{ .Values.createAdminTokenJob.priorityClassName | quote }}
      {{- end }}
      {{- if .Values.createAdminTokenJob.schedulerName }}
      schedulerName: {{ .Values.createAdminTokenJob.schedulerName }}
      {{- end }}
      {{- if .Values.podSecurityContext.enabled }}
      # We use the same security context as InfluxDB pods to avoid permission issues on shared PVC
      securityContext: {{- include "common.compatibility.renderSecurityContext" (dict "secContext" .Values.podSecurityContext "context" .) | nindent 8 }}
      {{- end }}
      initContainers:
        {{- if and .Values.defaultInitContainers.volumePermissions.enabled .Values.persistence.enabled (eq .Values.objectStore "file") }}
        {{- include "influxdb.defaultInitContainers.volumePermissions" . | nindent 8 }}
        {{- end }}
        - name: influxdb
          image: {{ include "influxdb.image" . }}
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          {{- if .Values.containerSecurityContext.enabled }}
          # We use the same security context as InfluxDB containers to avoid permission issues on shared PVC
          securityContext: {{- include "common.compatibility.renderSecurityContext" (dict "secContext" .Values.containerSecurityContext "context" .) | nindent 12 }}
          {{- end }}
          # We also use the same resources as InfluxDB to ensure we can start InfluxDB in background
          {{- if .Values.resources }}
          resources: {{- toYaml .Values.resources | nindent 12 }}
          {{- else if ne .Values.resourcesPreset "none" }}
          resources: {{- include "common.resources.preset" (dict "type" .Values.resourcesPreset) | nindent 12 }}
          {{- end }}
          command:
            - /bin/bash
          args:
            - -ec
            - |
              . /opt/bitnami/scripts/influxdb-env.sh
              . /opt/bitnami/scripts/libinfluxdb.sh

              {{- if eq .Values.objectStore "s3" }}
              check_s3() {
                  if curl --max-time {{ sub (int .Values.createAdminTokenJob.waitForS3.retryInterval) 1 }} -k "$AWS_ENDPOINT" | grep "RequestId"; then
                      return 0
                  else
                      return 1
                  fi
              }
              info "Waiting for S3 to be ready..."
              if ! retry_while check_s3 {{ int .Values.createAdminTokenJob.waitForS3.retryAttempts }} {{ int .Values.createAdminTokenJob.waitForS3.retryInterval }}; then
                  error "Error connecting to S3"
                  exit 1
              fi
              {{- end }}

              trap "influxdb_stop" EXIT
              influxdb_start_bg
              influxdb3_create_admin_token
              chmod 444 $INFLUXDB_AUTOGEN_ADMIN_TOKEN_FILE
          env:
            - name: BITNAMI_DEBUG
              value: {{ ternary "true" "false" (or .Values.image.debug .Values.diagnosticMode.enabled) | quote }}
            - name: INFLUXDB_OBJECT_STORE
              value: {{ .Values.objectStore | quote }}
            - name: INFLUXDB_DATA_DIR
              value: {{ printf "%s/data" .Values.persistence.mountPath | quote }}
            - name: INFLUXDB_NODE_ID
              value: {{ .Values.nodeId | quote }}
            - name: INFLUXDB_AUTOGEN_ADMIN_TOKEN_FILE
              value: "/shared/token"
            {{- if or (eq .Values.objectStore "s3") (eq .Values.objectStore "google") (eq .Values.objectStore "azure") }}
            - name: INFLUXDB3_BUCKET
              value: {{ .Values.bucket | quote }}
            {{- end }}
            {{- if eq .Values.objectStore "s3" }}
            {{- if .Values.s3.defaultRegion }}
            - name: AWS_DEFAULT_REGION
              value: {{ .Values.s3.defaultRegion | quote }}
            {{- end }}
            {{- if .Values.s3.endpoint }}
            - name: AWS_ENDPOINT
              value: {{ .Values.s3.endpoint | quote }}
            - name: AWS_ALLOW_HTTP
              value: {{ ternary "false" "true" (contains "https" .Values.s3.endpoint) | quote }}
            {{- end }}
            {{- if .Values.usePasswordFiles }}
            - name: AWS_ACCESS_KEY_ID_FILE
              value: "/opt/bitnami/influxdb/secrets/s3-access-key-id"
            - name: AWS_SECRET_ACCESS_KEY_FILE
              value: "/opt/bitnami/influxdb/secrets/s3-secret-access-key"
            {{- else }}
            - name: AWS_ACCESS_KEY_ID
              valueFrom:
                secretKeyRef:
                  name: {{ template "influxdb.store.secret.name" . }}
                  key: s3-access-key-id
            - name: AWS_SECRET_ACCESS_KEY
              valueFrom:
                secretKeyRef:
                  name: {{ template "influxdb.store.secret.name" . }}
                  key: s3-secret-access-key
            {{- end }}
            {{- else if eq .Values.objectStore "google" }}
            {{- if .Values.usePasswordFiles }}
            - name: GOOGLE_SERVICE_ACCOUNT_FILE
              value: "/opt/bitnami/influxdb/secrets/google-service-account-key"
            {{- else }}
            - name: GOOGLE_SERVICE_ACCOUNT
              valueFrom:
                secretKeyRef:
                  name: {{ template "influxdb.store.secret.name" . }}
                  key: google-service-account-key
            {{- end }}
            {{- else if eq .Values.objectStore "azure" }}
            - name: AZURE_STORAGE_ACCOUNT
              value: {{ .Values.azure.account | quote }}
            {{- if .Values.usePasswordFiles }}
            - name: AZURE_STORAGE_ACCESS_KEY_FILE
              value: "/opt/bitnami/influxdb/secrets/azure-storage-access-key"
            {{- else }}
            - name: AZURE_STORAGE_ACCESS_KEY
              valueFrom:
                secretKeyRef:
                  name: {{ template "influxdb.store.secret.name" . }}
                  key: azure-storage-access-key
            {{- end }}
            {{- end }}
          volumeMounts:
            - name: empty-dir
              mountPath: /tmp
              subPath: tmp-dir
            - name: empty-dir
              mountPath: /shared
              subPath: shared-dir
            - name: data
              mountPath: {{ .Values.persistence.mountPath }}
            {{- if and (or (eq .Values.objectStore "s3") (eq .Values.objectStore "google") (eq .Values.objectStore "azure")) .Values.usePasswordFiles }}
            - name: store-secret
              mountPath: /opt/bitnami/influxdb/secrets
              readOnly: true
            {{- end }}
      containers:
        - name: kubectl
          image: {{ include "influxdb.createAdminToken.image" . }}
          imagePullPolicy: {{ .Values.createAdminTokenJob.image.pullPolicy }}
          {{- if .Values.createAdminTokenJob.containerSecurityContext.enabled }}
          securityContext: {{- include "common.compatibility.renderSecurityContext" (dict "secContext" .Values.createAdminTokenJob.containerSecurityContext "context" .) | nindent 12 }}
          {{- end }}
          {{- if .Values.createAdminTokenJob.resources }}
          resources: {{- toYaml .Values.createAdminTokenJob.resources | nindent 12 }}
          {{- else if ne .Values.createAdminTokenJob.resourcesPreset "none" }}
          resources: {{- include "common.resources.preset" (dict "type" .Values.createAdminTokenJob.resourcesPreset) | nindent 12 }}
          {{- end }}
          command:
            - /bin/bash
          args:
            - -ec
            - |
              encoded_token="$(tr -d '\n' < /shared/token | base64 -w 0)"
              cat <<EOF | kubectl create -f -
              apiVersion: v1
              kind: Secret
              type: Opaque
              metadata:
                name: {{ include "common.names.fullname" . }}
                namespace: {{ include "common.names.namespace" . | quote }}
                labels: {{- include "common.labels.standard" (dict "customLabels" .Values.commonLabels "context" .) | nindent 18 }}
                  app.kubernetes.io/part-of: influxdb
                  app.kubernetes.io/component: influxdb
                {{- if .Values.commonAnnotations }}
                annotations: {{- include "common.tplvalues.render" (dict "value" .Values.commonAnnotations "context" .) | nindent 18 }}
                {{- end }}
              data:
                admin-token: $encoded_token
              EOF
          volumeMounts:
            - name: empty-dir
              mountPath: /tmp
              subPath: tmp-dir
            - name: empty-dir
              mountPath: /shared
              subPath: shared-dir
      volumes:
        - name: empty-dir
          emptyDir: {}
        {{- if and (or (eq .Values.objectStore "s3") (eq .Values.objectStore "google") (eq .Values.objectStore "azure")) .Values.usePasswordFiles }}
        - name: store-secret
          secret:
            secretName: {{ template "influxdb.store.secret.name" . }}
            defaultMode: 256
        {{- end }}
        - name: data
          {{- if .Values.persistence.enabled }}
          persistentVolumeClaim:
            claimName: {{ (tpl .Values.persistence.existingClaim .) | default (include "common.names.fullname" .) }}
          {{- else }}
          emptyDir: {}
          {{- end }}
{{- end }}
