---
apiVersion: v1
kind: ConfigMap
metadata:
  name: registry-velero-config
  labels:
    app: registry
data:
  backup.sh: |-
    #!/bin/sh
    set -euo pipefail
    echo 'backup starting ...'
    if [ -z "\$OBJECT_STORE_HOSTNAME" ]; then
      export OBJECT_STORE_HOSTNAME=\$OBJECT_STORE_CLUSTER_IP # included for backwards compatibility for snapshot restores with pre-ipv6 snapshot restores
    fi
    export S3_DIR=/backup/s3/
    export S3_BUCKET_NAME=docker-registry
    export S3_HOST=\$OBJECT_STORE_HOSTNAME
    rm -rf \$S3_DIR
    mkdir -p \$S3_DIR
    s3cmd --access_key=\$AWS_ACCESS_KEY_ID --secret_key=\$AWS_SECRET_ACCESS_KEY --host=\$S3_HOST --no-ssl --host-bucket=\$S3_BUCKET_NAME.\$S3_HOST sync s3://\$S3_BUCKET_NAME \$S3_DIR
    echo 'backup completed successfully'

  restore.sh: |-
    #!/bin/sh
    set -euo pipefail

    if [ -z "\$OBJECT_STORE_HOSTNAME" ]; then
      export OBJECT_STORE_HOSTNAME=\$OBJECT_STORE_CLUSTER_IP # included for backwards compatibility for snapshot restores with pre-ipv6 snapshot restores
    fi

    export S3_DIR=/backup/s3/
    export S3_BUCKET_NAME=docker-registry
    export S3_HOST=\$OBJECT_STORE_HOSTNAME
    echo 'restore starting ...'

    if [ ! -d \$S3_DIR ]; then
        exit 0
    fi

    export S3CMD_FLAGS=\"--access_key=\$AWS_ACCESS_KEY_ID --secret_key=\$AWS_SECRET_ACCESS_KEY --host=\$S3_HOST --no-ssl --host-bucket=\$S3_BUCKET_NAME.\$S3_HOST\"

    if s3cmd \$S3CMD_FLAGS ls s3://\$S3_BUCKET_NAME 2>&1 | grep -q 'NoSuchBucket'
    then
        echo "bucket \$S3_BUCKET_NAME does not exist, creating ..."
        s3cmd \$S3CMD_FLAGS mb s3://\$S3_BUCKET_NAME
    fi

    s3cmd \$S3CMD_FLAGS sync \$S3_DIR s3://\$S3_BUCKET_NAME
    rm -rf \$S3_DIR
    echo 'restore completed successfully'
