---
apiVersion: v1
kind: ConfigMap
metadata:
  name: velero-migrate-s3-config
  labels:
    app: velero
data:
  migrate-s3.sh: |-
    #!/bin/sh
    set -euo pipefail
    export S3_HOST=$OBJECT_STORE_CLUSTER_IP

    export ARCHIVES_DIR=/var/lib/velero
    export MIGRATION_FILE=$ARCHIVES_DIR/s3-migration.txt
    if [ -f $MIGRATION_FILE ]; then
        echo 'migration has already run. no-op.'
        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 bucket not found, skipping migration ..."
        exit 0
    fi

    echo 'object store detected, running migration ...'
    s3cmd $S3CMD_FLAGS sync s3://$S3_BUCKET_NAME $ARCHIVES_DIR
    echo 'migration ran successfully ...'
    echo 'recording that the migration ran ...'
    echo 'migration completed successfully $(date)'  > $MIGRATION_FILE
