{{- if .Values.backup.enabled }}
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "common.names.fullname" . }}-backup
  labels:
    {{- include "common.labels.standard" . | nindent 4 }}
    app.kubernetes.io/component: influxdb
    {{- if .Values.commonLabels }}
    {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }}
    {{- end }}
  {{- if .Values.commonAnnotations }}
  annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }}
  {{- end }}
data:
  backup.sh: |-
    #!/bin/bash

    set -e

    . /opt/bitnami/scripts/libinfluxdb.sh

    DATE="$(date +%Y%m%d_%H%M%S)"

    host="{{ include "common.names.fullname" . }}.{{ .Release.Namespace }}.svc"

    get_orgs() {
      INFLUX_TOKEN="${INFLUXDB_ADMIN_USER_TOKEN}" influx org list --host "http://${host}:{{ coalesce .Values.influxdb.service.ports.http .Values.influxdb.service.port }}" 2> /dev/null | grep -v 'ID' | awk -F '\t' 'BEGIN{ORS=" "} {print $2}'
    }

    get_databases() {
        local org_name="${1:-}"
        INFLUX_TOKEN="${INFLUXDB_ADMIN_USER_TOKEN}" influx bucket list --host "http://${host}:{{ coalesce .Values.influxdb.service.ports.http .Values.influxdb.service.port }}" --org "${org_name}" 2> /dev/null | grep -v 'ID' | awk -F '\t' 'BEGIN{ORS=" "} {print $2}'
    }

    for ORG in $(get_orgs); do
        echo "finding buckets in org ${ORG}"
        for BUCKET in $(get_databases "${ORG}"); do
            backup_dir="{{ .Values.backup.directory }}/${ORG}/${BUCKET}"
            echo "backuping ${BUCKET} bucket to ${backup_dir}"
            mkdir -p "${backup_dir}"

            INFLUX_TOKEN="${INFLUXDB_ADMIN_USER_TOKEN}" influx backup --host "http://${host}:{{ coalesce .Values.influxdb.service.ports.http .Values.influxdb.service.port }}" --bucket "${BUCKET}" "${backup_dir}/${DATE}"
        done
    done

    echo "deleting old backups"
    find {{ .Values.backup.directory }} -mindepth 3 -maxdepth 3 -not -name ".snapshot" -not -name "lost+found" -type d -mtime +{{ .Values.backup.retentionDays }} -exec rm -r {} \;
  upload-google.sh: |-
    #!/bin/sh

    set -e

    gcloud auth activate-service-account --key-file /var/secrets/google/{{ .Values.backup.uploadProviders.google.secretKey }}
    gsutil -m rsync -r -d {{ .Values.backup.directory }}/ {{ .Values.backup.uploadProviders.google.bucketName }}
  upload-azure.sh: |-
    #!/bin/sh

    set -e

    az storage blob sync --source {{ .Values.backup.directory }} --container {{ .Values.backup.uploadProviders.azure.containerName }}
  upload-aws.sh: |-
    #!/bin/sh

    set -e

    aws s3 sync {{ .Values.backup.directory }} {{ .Values.backup.uploadProviders.aws.bucketName }}
{{ end }}
