{{- if .Values.backup.enabled }}
---
apiVersion: v1
kind: Secret
metadata:
  name: {{ .Release.Name }}-backup-script
stringData:
  backup.sh: |
    #!/bin/sh
    set -e
    set -o pipefail

    JOB_ID="job-$(uuidgen|cut -f1 -d-)"
    DB_LIST=$(mysql -u "$MYSQL_USER" -h "$MYSQL_HOST" -sNe 'SHOW DATABASES;' | grep -v '^\(#.*\|mysql\|sys\|information_schema\|performance_schema\)$')
    echo DB_LIST=$(echo "$DB_LIST" | shuf) # shuffle list
    echo "Job ID: $JOB_ID"
    echo "Target repo: $REPO_PREFIX"
    echo "Cleanup strategy: $CLEANUP_STRATEGY"
    echo "Start backup for:"
    echo "$DB_LIST"
    echo
    echo "Backup started at `date +%Y-%m-%d\ %H:%M:%S`"
    for db in $DB_LIST; do
      (
        set -x
        restic -r "s3:${REPO_PREFIX}/$db" cat config >/dev/null 2>&1 || \
          restic -r "s3:${REPO_PREFIX}/$db" init --repository-version 2
        restic -r "s3:${REPO_PREFIX}/$db" unlock --remove-all >/dev/null 2>&1 || true # no locks, k8s takes care of it
        mysqldump -u "$MYSQL_USER" -h "$MYSQL_HOST" --single-transaction --databases $db | \
          restic -r "s3:${REPO_PREFIX}/$db" backup --tag "$JOB_ID" --stdin --stdin-filename dump.sql 
        restic -r "s3:${REPO_PREFIX}/$db" tag --tag "$JOB_ID" --set "completed"
      )
    done
    echo "Backup finished at `date +%Y-%m-%d\ %H:%M:%S`"

    echo
    echo "Run cleanup:"
    echo

    echo "Cleanup started at `date +%Y-%m-%d\ %H:%M:%S`"
    for db in $DB_LIST; do
      (
        set -x
        restic forget -r "s3:${REPO_PREFIX}/$db" --group-by=tags --keep-tag "completed" # keep completed snapshots only
        restic forget -r "s3:${REPO_PREFIX}/$db" --group-by=tags $CLEANUP_STRATEGY
        restic prune -r "s3:${REPO_PREFIX}/$db"
      )
    done
    echo "Cleanup finished at `date +%Y-%m-%d\ %H:%M:%S`"
{{- end }}
