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

{{- if .Values.preUpgradeJob.enabled }}
apiVersion: {{ include "common.capabilities.job.apiVersion" . }}
kind: Job
metadata:
  name: {{ include "common.names.fullname" . }}-pre-upgrade
  namespace: {{ .Release.Namespace | quote }}
  labels: {{- include "common.labels.standard" ( dict "customLabels" .Values.commonLabels "context" $ ) | nindent 4 }}
    app.kubernetes.io/component: etcd-pre-upgrade-job
  {{- $defaultAnnotations := dict "helm.sh/hook" "pre-upgrade" "helm.sh/hook-delete-policy" "before-hook-creation" }}
  {{- $annotations := include "common.tplvalues.merge" ( dict "values" ( list .Values.preUpgradeJob.annotations .Values.commonAnnotations $defaultAnnotations ) "context" . ) }}
  annotations: {{- include "common.tplvalues.render" ( dict "value" $annotations "context" $ ) | nindent 4 }}
spec:
  {{- $podLabels := include "common.tplvalues.merge" ( dict "values" ( list .Values.preUpgradeJob.podLabels .Values.commonLabels ) "context" . ) }}
  template:
    metadata:
      labels: {{- include "common.labels.standard" ( dict "customLabels" $podLabels "context" $ ) | nindent 8 }}
        app.kubernetes.io/component: etcd-pre-upgrade-job
      annotations:
        {{- if .Values.preUpgradeJob.podAnnotations }}
        {{- include "common.tplvalues.render" ( dict "value" .Values.preUpgradeJob.podAnnotations "context" $) | nindent 8 }}
        {{- end }}
        {{- if (include "etcd.createConfigmap" .) }}
        checksum/configuration: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }}
        {{- end }}
        {{- if (include "etcd.token.createSecret" .) }}
        checksum/token-secret: {{ include (print $.Template.BasePath "/token-secrets.yaml") . | sha256sum }}
        {{- end }}
    spec:
      {{- include "etcd.imagePullSecrets" . | nindent 6 }}
      automountServiceAccountToken: {{ .Values.automountServiceAccountToken }}
      {{- if .Values.affinity }}
      affinity: {{- include "common.tplvalues.render" (dict "value" .Values.affinity "context" $) | nindent 8 }}
      {{- else }}
      affinity:
        podAffinity: {{- include "common.affinities.pods" (dict "type" .Values.podAffinityPreset "component" "etcd-pre-upgrade-job" "customLabels" $podLabels "context" $) | nindent 10 }}
        podAntiAffinity: {{- include "common.affinities.pods" (dict "type" .Values.podAntiAffinityPreset "component" "etcd-pre-upgrade-job" "customLabels" $podLabels "context" $) | nindent 10 }}
        nodeAffinity: {{- include "common.affinities.nodes" (dict "type" .Values.nodeAffinityPreset.type "key" .Values.nodeAffinityPreset.key "values" .Values.nodeAffinityPreset.values) | nindent 10 }}
      {{- end }}
      {{- if .Values.podSecurityContext.enabled }}
      securityContext: {{- include "common.compatibility.renderSecurityContext" (dict "secContext" .Values.podSecurityContext "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.nodeSelector }}
      nodeSelector: {{- include "common.tplvalues.render" (dict "value" .Values.nodeSelector "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.tolerations }}
      tolerations: {{- include "common.tplvalues.render" (dict "value" .Values.tolerations "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.terminationGracePeriodSeconds }}
      terminationGracePeriodSeconds: {{ .Values.terminationGracePeriodSeconds }}
      {{- end }}
      {{- if .Values.schedulerName }}
      schedulerName: {{ .Values.schedulerName }}
      {{- end }}
      {{- if .Values.topologySpreadConstraints }}
      topologySpreadConstraints: {{- include "common.tplvalues.render" (dict "value" .Values.topologySpreadConstraints "context" .) | nindent 8 }}
      {{- end }}
      restartPolicy: Never
      containers:
        {{- $replicaCount := int .Values.replicaCount }}
        {{- $clientPort := int .Values.containerPorts.client }}
        {{- $etcdFullname := include "common.names.fullname" . }}
        {{- $releaseNamespace := .Release.Namespace }}
        {{- $etcdHeadlessServiceName := (printf "%s-%s" $etcdFullname "headless" | trunc 63 | trimSuffix "-") }}
        {{- $clusterDomain := .Values.clusterDomain }}
        {{- $etcdClientProtocol := include "etcd.clientProtocol" . }}
        - name: pre-upgrade-job
          image: {{ include "etcd.image" . }}
          imagePullPolicy: {{ .Values.image.pullPolicy | quote }}
          {{- if .Values.preUpgradeJob.containerSecurityContext.enabled }}
          securityContext: {{- include "common.compatibility.renderSecurityContext" (dict "secContext" .Values.preUpgradeJob.containerSecurityContext "context" $) | nindent 12 }}
          {{- end }}
          command: [ "/opt/bitnami/scripts/etcd/entrypoint.sh" ]
          args: [ "/opt/bitnami/scripts/etcd/preupgrade.sh" ]
          env:
            - name: BITNAMI_DEBUG
              value: {{ ternary "true" "false" (or .Values.image.debug .Values.diagnosticMode.enabled) | quote }}
            - name: ETCD_ON_K8S
              value: "yes"
            - name: ETCD_DATA_DIR
              value: "/bitnami/etcd/data"
            {{- if or .Values.auth.rbac.create .Values.auth.rbac.enabled }}
            {{- if .Values.usePasswordFiles }}
            - name: ETCD_ROOT_PASSWORD_FILE
              value: {{ printf "/opt/bitnami/etcd/secrets/%s" (include "etcd.secretPasswordKey" .) }}
            {{- else }}
            - name: ETCD_ROOT_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ include "etcd.secretName" . }}
                  key: {{ include "etcd.secretPasswordKey" . }}
            {{- end }}
            {{- end }}
            {{- $initialCluster := list }}
            {{- range $e, $i := until $replicaCount }}
            {{- $initialCluster = append $initialCluster (printf "%s-%d=%s://%s-%d.%s.%s.svc.%s:%d" $etcdFullname $i $etcdClientProtocol $etcdFullname $i $etcdHeadlessServiceName $releaseNamespace $clusterDomain $clientPort) }}
            {{- end }}
            - name: ETCD_INITIAL_CLUSTER
              value: {{ join "," $initialCluster | quote }}
            {{- if and .Values.auth.client.secureTransport .Values.auth.client.useAutoTLS }}
            - name: ETCD_AUTO_TLS
              value: "true"
            {{- else if .Values.auth.client.secureTransport }}
            - name: ETCD_CERT_FILE
              value: "/opt/bitnami/etcd/certs/client/{{ .Values.auth.client.certFilename }}"
            - name: ETCD_KEY_FILE
              value: "/opt/bitnami/etcd/certs/client/{{ .Values.auth.client.certKeyFilename }}"
            {{- if .Values.auth.client.enableAuthentication }}
            - name: ETCD_CLIENT_CERT_AUTH
              value: "true"
            - name: ETCD_TRUSTED_CA_FILE
              value: "/opt/bitnami/etcd/certs/client/{{ .Values.auth.client.caFilename | default "ca.crt" }}"
            {{- else if .Values.auth.client.caFilename }}
            - name: ETCD_TRUSTED_CA_FILE
              value: "/opt/bitnami/etcd/certs/client/{{ .Values.auth.client.caFilename }}"
            {{- else }}
            - name: ETCD_EXTRA_AUTH_FLAGS
              value: "--insecure-skip-tls-verify"
            {{- end }}
            {{- end }}
            {{- if .Values.extraEnvVars }}
            {{- include "common.tplvalues.render" (dict "value" .Values.extraEnvVars "context" $) | nindent 12 }}
            {{- end }}
          envFrom:
            {{- if .Values.extraEnvVarsCM }}
            - configMapRef:
                name: {{ include "common.tplvalues.render" (dict "value" .Values.extraEnvVarsCM "context" $) }}
            {{- end }}
            {{- if .Values.extraEnvVarsSecret }}
            - secretRef:
                name: {{ include "common.tplvalues.render" (dict "value" .Values.extraEnvVarsSecret "context" $) }}
            {{- end }}
          {{- if .Values.preUpgradeJob.resources }}
          resources: {{- include "common.tplvalues.render" (dict "value" .Values.preUpgradeJob.resources "context" $) | nindent 12 }}
          {{- else if ne .Values.preUpgradeJob.resourcesPreset "none" }}
          resources: {{- include "common.resources.preset" (dict "type" .Values.preUpgradeJob.resourcesPreset) | nindent 12 }}
          {{- end }}
          volumeMounts:
            {{- if or .Values.configuration .Values.existingConfigmap }}
            - name: configuration
              mountPath: /opt/bitnami/etcd/conf/
            {{- else }}
            - name: empty-dir
              mountPath: /opt/bitnami/etcd/conf/
              subPath: app-conf-dir
            {{- end }}
            - name: empty-dir
              mountPath: /tmp
              subPath: tmp-dir
            {{- if and (eq .Values.auth.token.enabled true) (eq .Values.auth.token.type "jwt") }}
            - name: etcd-jwt-token
              mountPath: /opt/bitnami/etcd/certs/token/
              readOnly: true
            {{- end }}
            {{- if or .Values.auth.client.enableAuthentication (and .Values.auth.client.secureTransport (not .Values.auth.client.useAutoTLS )) }}
            - name: etcd-client-certs
              mountPath: /opt/bitnami/etcd/certs/client/
              readOnly: true
            {{- end }}
            {{- if and .Values.usePasswordFiles (or .Values.auth.rbac.create .Values.auth.rbac.enabled) }}
            - name: etcd-secrets
              mountPath: /opt/bitnami/etcd/secrets
            {{- end }}
            {{- if .Values.extraVolumeMounts }}
            {{- include "common.tplvalues.render" (dict "value" .Values.extraVolumeMounts "context" $) | nindent 12 }}
            {{- end }}
      volumes:
        - name: empty-dir
          emptyDir: {}
        {{- if or .Values.configuration .Values.existingConfigmap }}
        - name: configuration
          configMap:
            name: {{ include "etcd.configmapName" . }}
        {{- end }}
        {{- if and (eq .Values.auth.token.enabled true) (eq .Values.auth.token.type "jwt") }}
        - name: etcd-jwt-token
          secret:
            secretName: {{ include "etcd.token.secretName" . }}
            defaultMode: 256
        {{- end }}
        {{- if or .Values.auth.client.enableAuthentication (and .Values.auth.client.secureTransport (not .Values.auth.client.useAutoTLS )) }}
        - name: etcd-client-certs
          secret:
            secretName: {{ required "A secret containing the client certificates is required" (tpl .Values.auth.client.existingSecret .) }}
            defaultMode: 256
        {{- end }}
        {{- if and .Values.usePasswordFiles (or .Values.auth.rbac.create .Values.auth.rbac.enabled) }}
        - name: etcd-secrets
          projected:
            sources:
              - secret:
                  name:  {{ include "etcd.secretName" . }}
        {{- end }}
        {{- if .Values.extraVolumes }}
        {{- include "common.tplvalues.render" (dict "value" .Values.extraVolumes "context" $) | nindent 8 }}
        {{- end }}
{{- end }}
