#!/bin/bash
set -euxo pipefail

today=`date +"%Y-%m-%d"`
echo $today
dump_file=/tmp/myskillbox_backup.dump

# look up the list of backups from the heroku cli,
# then look for the first line of the backup list and
# look for today's date. script fails if nothing is found
# (grep exits with an error code)
heroku pg:backups --app $APP_NAME | grep '=== Backups' -A 3 | grep -q $today
heroku pg:backups:download --app $APP_NAME --output=$dump_file
# gzip it
gzip $dump_file
# encrypt the backup file
gpg --yes --passphrase=$PG_BACKUP_KEY --batch -c $dump_file.gz
rm $dump_file.gz

BACKUP_FILE_NAME="myskillbox-pg-backup-$(date '+%Y-%m-%d_%H.%M').gpg"

# temporarily set the access key, because we use a different one for the backup and
# the default S3 bucket for Django
AWS_ACCESS_KEY_ID=$BACKUP_AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY=$BACKUP_AWS_SECRET_ACCESS_KEY
aws s3 cp $dump_file.gz.gpg "s3://${BACKUP_S3_BUCKET_NAME}/${BACKUP_FILE_NAME}"
rm $dump_file.gz.gpg
