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

{{- if .Values.defrag.enabled }}
apiVersion: {{ include "common.capabilities.cronjob.apiVersion" . }}
kind: CronJob
metadata:
  name: {{ printf "%s-defrag" (include "common.names.fullname" .) | trunc 63 | trimSuffix "-" }}
  namespace: {{ include "common.names.namespace" . | quote }}
  {{- $labels := include "common.tplvalues.merge" ( dict "values" ( list .Values.defrag.cronjob.labels .Values.commonLabels ) "context" . ) }}
  labels: {{- include "common.labels.standard" ( dict "customLabels" $labels "context" $ ) | nindent 4 }}
  {{- if or .Values.defrag.cronjob.annotations .Values.commonAnnotations }}
  {{- $annotations := include "common.tplvalues.merge" ( dict "values" ( list .Values.defrag.cronjob.annotations .Values.commonAnnotations ) "context" . ) }}
  annotations: {{- include "common.tplvalues.render" ( dict "value" $annotations "context" $) | nindent 4 }}
  {{- end }}
spec:
  {{- if .Values.defrag.cronjob.startingDeadlineSeconds }}
  startingDeadlineSeconds: {{ .Values.defrag.cronjob.startingDeadlineSeconds }}
  {{- end }}
  concurrencyPolicy: {{ .Values.defrag.cronjob.concurrencyPolicy }}
  schedule: {{ .Values.defrag.cronjob.schedule | quote }}
  suspend: {{ .Values.defrag.cronjob.suspend }}
  successfulJobsHistoryLimit: {{ .Values.defrag.cronjob.successfulJobsHistoryLimit }}
  failedJobsHistoryLimit: {{ .Values.defrag.cronjob.failedJobsHistoryLimit }}
  jobTemplate:
    spec:
      template:
        metadata:
          {{- $mergedLabels := mergeOverwrite (dict) .Values.commonLabels .Values.defrag.cronjob.podLabels }}
          labels: {{- include "common.labels.standard" ( dict "customLabels" $mergedLabels "context" $ ) | nindent 12 }}
          {{- if .Values.defrag.cronjob.podAnnotations }}
          annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.defrag.cronjob.podAnnotations "context" $) | nindent 12 }}
          {{- end }}
        spec:
          {{- if .Values.defrag.cronjob.activeDeadlineSeconds }}
          activeDeadlineSeconds: {{ .Values.defrag.cronjob.activeDeadlineSeconds }}
          {{- end }}
          restartPolicy: {{ .Values.defrag.cronjob.restartPolicy }}
          {{- if .Values.defrag.cronjob.podSecurityContext.enabled }}
          securityContext: {{- include "common.compatibility.renderSecurityContext" (dict "secContext" .Values.defrag.cronjob.podSecurityContext "context" $) | nindent 12 }}
          {{- end }}
          {{- if .Values.defrag.cronjob.nodeSelector }}
          nodeSelector: {{- include "common.tplvalues.render" (dict "value" .Values.defrag.cronjob.nodeSelector "context" $) | nindent 12 }}
          {{- end }}
          {{- if .Values.defrag.cronjob.tolerations }}
          tolerations: {{- include "common.tplvalues.render" (dict "value" .Values.defrag.cronjob.tolerations "context" $) | nindent 12 }}
          {{- end }}
          {{- if .Values.defrag.cronjob.serviceAccountName }}
          serviceAccountName: {{ .Values.defrag.cronjob.serviceAccountName | quote }}
          {{- end }}
          containers:
            - name: etcd-defrag
              image: {{ include "etcd.image" . }}
              imagePullPolicy: "IfNotPresent"
              {{- if .Values.defrag.cronjob.containerSecurityContext.enabled }}
              securityContext: {{- include "common.compatibility.renderSecurityContext" (dict "secContext" .Values.defrag.cronjob.containerSecurityContext "context" $) | nindent 16 }}
              {{- end }}
              env:
                - name: BITNAMI_DEBUG
                  value: {{ ternary "true" "false" (or .Values.image.debug .Values.diagnosticMode.enabled) | quote }}
                {{- if and .Values.auth.rbac.create .Values.auth.token.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 }}
                {{- if or .Values.auth.client.enableAuthentication (and .Values.auth.client.secureTransport (not .Values.auth.client.useAutoTLS )) }}
                - name: ETCDCTL_CACERT
                  value: "/opt/bitnami/etcd/certs/client/{{ .Values.auth.client.caFilename | default "ca.crt" }}"
                - name: ETCDCTL_KEY
                  value: "/opt/bitnami/etcd/certs/client/{{ .Values.auth.client.certKeyFilename }}"
                - name: ETCDCTL_CERT
                  value: "/opt/bitnami/etcd/certs/client/{{ .Values.auth.client.certFilename }}"
                {{- end }}
                {{- if .Values.defrag.cronjob.extraEnvVars }}
                {{- include "common.tplvalues.render" (dict "value" .Values.extraEnvVars "context" $) | nindent 12 }}
                {{- end }}
              {{- if or .Values.defrag.cronjob.extraEnvVarsCM .Values.defrag.cronjob.extraEnvVarsSecret }}
              envFrom:
                {{- if .Values.defrag.cronjob.extraEnvVarsCM }}
                - configMapRef:
                    name: {{ include "common.tplvalues.render" (dict "value" .Values.defrag.cronjob.extraEnvVarsCM "context" $) }}
                {{- end }}
                {{- if .Values.defrag.cronjob.extraEnvVarsSecret }}
                - secretRef:
                    name: {{ include "common.tplvalues.render" (dict "value" .Values.defrag.cronjob.extraEnvVarsSecret "context" $) }}
                {{- end }}
              {{- end }}
              {{- if .Values.defrag.cronjob.command }}
              command: {{ .Values.defrag.cronjob.command | toYaml | nindent 16 }}
              {{- else }}
              command: 
                - /bin/bash
                - -c
                - |-
                  #!/usr/bin/env bash
                  set -eo pipefail

                  # Include library
                  . /opt/bitnami/scripts/libetcd.sh

                  # Load etcd environment settings
                  . /opt/bitnami/scripts/etcd-env.sh

                  # Common flags
                  read -r -a flags <<<"$(etcdctl_auth_flags)"
                  cmd="etcdctl --command-timeout=60s ${flags[@]}"
                  {{- $etcdFullname := include "common.names.fullname" . }}
                  {{- $etcdHeadlessServiceName := (printf "%s-%s" $etcdFullname "headless" | trunc 63 | trimSuffix "-") }}
                  {{- $namespace := include "common.names.namespace" . }}
                  {{- $clusterDomain := .Values.clusterDomain }}
                  {{- $port := int .Values.service.ports.client }}
                  {{- $endpointStr := "" }}
                  {{- $replicaCount := (int .Values.replicaCount) }}
                  {{- $releaseNamespace := include "common.names.namespace" . }}
                  {{- range $iEndpoint, $e := until $replicaCount }}
                  {{- $endpoint := printf "%s://%s-%d.%s.%s.svc.%s:%d" (include "etcd.clientProtocol" $) $etcdFullname $iEndpoint $etcdHeadlessServiceName $namespace $clusterDomain $port }}
                  {{- $endpointStr = printf "%s%s" $endpointStr $endpoint }}
                  {{- if ne $iEndpoint (sub $replicaCount 1) }}
                  {{- $endpointStr = printf "%s," $endpointStr }}
                  {{- end }}
                  {{- end }}
                  {{- $endpointStr = printf "%s" $endpointStr }}
                  $cmd --endpoints={{ $endpointStr | quote}} defrag
              {{- end }}
              {{- if .Values.defrag.cronjob.args }}
              args: {{ .Values.defrag.cronjob.args | toYaml | nindent 16 }}
              {{- end }}
              {{- if .Values.defrag.cronjob.resources }}
              resources: {{- toYaml .Values.defrag.cronjob.resources | nindent 16 }}
              {{- else if ne .Values.defrag.cronjob.resourcesPreset "none" }}
              resources: {{- include "common.resources.preset" (dict "type" .Values.defrag.cronjob.resourcesPreset) | nindent 16 }}
              {{- end }}
              volumeMounts:
              {{- 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/
                  readOnly: true
              {{- end }}
          {{- if or .Values.auth.client.enableAuthentication (and .Values.auth.client.secureTransport (not .Values.auth.client.useAutoTLS )) (and .Values.usePasswordFiles (or .Values.auth.rbac.create .Values.auth.rbac.enabled)) }}
          volumes:
            {{- 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 }}
          {{- end }}
{{- end }}
