{{- if .Values.defragmentation.schedule -}}
apiVersion: batch/v1
kind: CronJob
metadata:
  labels:
    {{- include "etcd.labels" . | nindent 4 }}
  name: "{{ .Release.Name }}-defrag"
  namespace: {{ .Release.Namespace }}
spec:
  schedule: "{{ .Values.defragmentation.schedule }}"
  successfulJobsHistoryLimit: 4
  jobTemplate:
    spec:
      template:
        spec:
          serviceAccountName: {{ include "etcd.serviceAccountName" . }}
          restartPolicy: OnFailure
          containers:
          - name: etcd-client
            image: {{ include "etcd.fullyQualifiedDockerImage" . }}
            imagePullPolicy: {{ .Values.image.pullPolicy }}
            command:
              - bash
              - -c
              - |-
                for ENDPOINT in {{ include "etcd.endpoints" . }}; do
                  etcdctl --endpoints=https://${ENDPOINT} defrag;
                  etcdctl --endpoints=https://${ENDPOINT} alarm disarm;
                  etcdctl --endpoints=https://${ENDPOINT} alarm list;
                  etcdctl --endpoints=https://${ENDPOINT} endpoint status -w table;
                  etcdctl --endpoints=https://${ENDPOINT} member list -w table;
                  sleep 15;
                done;
            env:
            - name: ETCDCTL_CACERT
              value: /opt/certs/ca/ca.crt
            - name: ETCDCTL_CERT
              value: /opt/certs/root-client-certs/tls.crt
            - name: ETCDCTL_KEY
              value: /opt/certs/root-client-certs/tls.key
            volumeMounts:
            - name: root-client-certs
              mountPath: /opt/certs/root-client-certs
            - name: certs
              mountPath: /opt/certs/ca
          securityContext:
            runAsUser: 1000
            runAsGroup: 1000
            fsGroup: 1000
          {{- with .Values.tolerations }}
          tolerations: {{- toYaml . | nindent 12 }}
          {{- end }}
          volumes:
          - name: root-client-certs
            secret:
              secretName: {{ include "etcd.clientSecretName" . }}
              optional: true
          - name: certs
            secret:
              secretName: {{ include "etcd.caSecretName" . }}
              optional: true
{{- end }}
