apiVersion: v1
kind: ConfigMap
metadata:
  name: rds-backup-scripts
data:
  create-manual-backup.sh: |
    #!/bin/bash
    datestamp=$(date +%F)
    function createBackup()
    {
      echo "[$(date +%T)] Starting to create a auto manual backup of rds {{ .Values.otcRDS.name }} "

      rds_backup_id=$(
        openstack rds backup create \
          --description "backup from {{ .Values.otcRDS.name }}-$datestamp" \
          "{{ .Release.Name }}-{{ .Values.otcRDS.name }}-$datestamp" \
          {{ .Values.otcRDS.name }} -f json | \
          jq --raw-output '.id'
      )
      if [ -z $rds_backup_id ]; then
          exit 1
      fi

      echo " Creating Backup {{ .Values.otcRDS.name }}-$datestamp in progress..."
      size=0
      while [[ $size -eq 0 ]]
      do
        size=$(openstack rds backup list --backup-id $rds_backup_id {{ .Values.otcRDS.name }} -f json | jq --raw-output '.[] | ."Size (KB)"')
        if [ -z $size ]; then
          exit 1
        fi
        sleep 15
      done
      echo "[$(date +%T)] Finished with manual rds backup of db: {{ .Values.otcRDS.name }}"
    }
    createBackup

  cleanup-manual-backups.sh: |
    function keepOnlyLastNBackups() {
      num_backups_to_keep="$1"
    
      # seems to remove with offset the newest N backups. Not influenced by sorting
      openstack rds backup list --backup-type="manual" --offset="$num_backups_to_keep" --format=json "{{ .Values.otcRDS.name }}" | \
        jq '.[].ID' | \
        xargs -I %% sh -c 'echo "[$(date +%T)] Removing backup with id %% on {{ .Values.otcRDS.name }}"; openstack rds backup delete %%'
    }
    
    keepOnlyLastNBackups {{ .Values.keepDays }}
