#!/usr/bin/env bash
# The production database's nightly copy (deploy/production-hestia/README.md). Hestia's cron of the user rebonusapp
# runs it at 04:30, before Hestia's own backup (05:10), which takes the domain's folder — these copies with it — to
# Timeweb's backup server in Saint Petersburg. The role loyal_backup reads every row (BYPASSRLS, pg_read_all_data) and
# changes nothing; its password is in ~/.pgpass. The copies hold the phones and e-mails encrypted: their keys stay out
# of every backup (the owner keeps a copy). Seven copies are kept.
set -euo pipefail
umask 077

DIR=/home/rebonusapp/web/app.rebonus.ru/private/backups
KEEP=7

mkdir -p "$DIR"
file="$DIR/rebonus-$(date +%F-%H%M).dump"
pg_dump --host=127.0.0.1 --port=5433 --username=loyal_backup --no-password --format=custom --file="$file.part" rebonus
mv "$file.part" "$file"

# The newest seven stay; a copy that failed half-way (.part) goes too.
ls -1t "$DIR"/rebonus-*.dump | tail -n +$((KEEP + 1)) | xargs -r rm -f
find "$DIR" -name '*.part' -mmin +60 -delete
