{{- if .Values.backup.enabled }}
{{- $release := .Release }}
{{- $values := .Values }}
{{- $backup := $values.backup }}
{{- range $index, $schedule := $backup.schedule }}
---
apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: {{ template "cassandra.fullname" $ }}-backup-{{ $schedule.keyspace }}
  labels:
    app: {{ template "cassandra.name" $ }}-cain
    chart: {{ template "cassandra.chart" $ }}
    release: "{{ $release.Name }}"
    heritage: "{{ $release.Service }}"
spec:
  schedule: {{ $schedule.cron | quote }}
  concurrencyPolicy: Forbid
  startingDeadlineSeconds: 120
  jobTemplate:
    spec:
      template:
        metadata:
          annotations:
            {{ toYaml $backup.annotations }}
        spec:
          restartPolicy: OnFailure
          serviceAccountName: {{ template "cassandra.serviceAccountName" $ }}
          containers:
          - name: cassandra-backup
            image: "{{ $backup.image.repos }}:{{ $backup.image.tag }}"
            command: ["cain"]
            args:
            - backup
            - --namespace
            - {{ $release.Namespace }}
            - --selector
            - release={{ $release.Name }},app={{ template "cassandra.name" $ }}
            - --keyspace
            - {{ $schedule.keyspace }}
            - --dst
            - {{ $backup.destination }}
            {{- with $backup.extraArgs }}
{{ toYaml . | indent 12 }}
          {{- end }}
          {{- with $backup.env }}
            env:
{{ toYaml . | indent 12 }}
          {{- end }}
          {{- with $backup.resources }}
            resources:
{{ toYaml . | indent 14 }}
          {{- end }}
        affinity:
          podAffinity:
            preferredDuringSchedulingIgnoredDuringExecution:
            - labelSelector:
                matchExpressions:
                - key: app
                  operator: In
                  values:
                  - {{ template "cassandra.fullname" $ }}
                - key: release
                  operator: In
                  values:
                  - {{ $release.Name }}
              topologyKey: "kubernetes.io/hostname"
      {{- with $values.tolerations }}
        tolerations:
{{ toYaml . | indent 10 }}
      {{- end }}
{{- end }}
{{- end }}
