#!/usr/bin/env bash
# Daily production backup.
# - Local point-in-time archives (DB dump + uploads tarball), 7 days retention.
# - Off-site copy on the staging server: DB dumps (14 days) + incremental
#   uploads mirror (rsync, single current copy — the staging server is short
#   on disk, so no remote tarball history).
# Installed at /opt/church-website/scripts/backup.sh, run by
# /etc/cron.d/church-website-backup.
set -euo pipefail

DATE=$(date +%F)
BACKUP_DIR=/opt/backups
REMOTE=root@178.104.35.59
REMOTE_DIR=/opt/backups/production
VOLUMES_DIR=/var/lib/docker/volumes

mkdir -p "$BACKUP_DIR"

# Local point-in-time backups
docker exec postgres pg_dump -U postgres -Fc church_website > "$BACKUP_DIR/db-$DATE.dump"
tar -czf "$BACKUP_DIR/uploads-$DATE.tar.gz" -C "$VOLUMES_DIR" \
  uploads-production-media/_data uploads-production-documents/_data

# Off-site copy to the staging server
ssh -o StrictHostKeyChecking=accept-new "$REMOTE" "mkdir -p $REMOTE_DIR/db $REMOTE_DIR/uploads/media $REMOTE_DIR/uploads/documents"
scp -q "$BACKUP_DIR/db-$DATE.dump" "$REMOTE:$REMOTE_DIR/db/"
rsync -a --delete "$VOLUMES_DIR/uploads-production-media/_data/" "$REMOTE:$REMOTE_DIR/uploads/media/"
rsync -a --delete "$VOLUMES_DIR/uploads-production-documents/_data/" "$REMOTE:$REMOTE_DIR/uploads/documents/"

# Retention
find "$BACKUP_DIR" -type f -mtime +7 -delete
ssh "$REMOTE" "find $REMOTE_DIR/db -type f -mtime +14 -delete"

echo "$(date -Is) backup OK: db-$DATE.dump + uploads-$DATE.tar.gz (local), synced to $REMOTE"
