#!/bin/bash
# Database dump + uploaded files (receipt PDFs, logos, UPI QR) to S3.
# Runs from /etc/cron.d/greenathon as the greenathon user. Settings: /etc/greenathon/backup.env
# APP_KEY and BLIND_INDEX_KEY are deliberately NOT backed up here: keep them in your password manager.
set -Eeuo pipefail
source /etc/greenathon/backup.env      # BACKUP_BUCKET, DB_NAME, AWS_DEFAULT_REGION (exported)
APP=${GREENATHON_APP:-/var/www/greenathon}
DIR=/var/backups/greenathon
TS=$(date +%F-%H%M)
mkdir -p "$DIR"

mysqldump --defaults-extra-file="$APP/shared/.my.cnf" --single-transaction --quick \
    --routines --triggers --no-tablespaces --set-gtid-purged=OFF "$DB_NAME" | gzip -9 > "$DIR/db-$TS.sql.gz.part"
mv "$DIR/db-$TS.sql.gz.part" "$DIR/db-$TS.sql.gz"

aws s3 cp "$DIR/db-$TS.sql.gz" "s3://$BACKUP_BUCKET/db/db-$TS.sql.gz" --only-show-errors
aws s3 sync "$APP/shared/storage/app/private" "s3://$BACKUP_BUCKET/files/" --only-show-errors \
    --exclude "livewire-tmp/*"

find "$DIR" -name 'db-*.sql.gz' -mtime +3 -delete
echo "$(date -Is) backup ok: db-$TS.sql.gz ($(du -h "$DIR/db-$TS.sql.gz" | cut -f1))"
