#!/usr/bin/env bash
# Nightly backup: MySQL dump + private storage (reports, logo) + .env, rotated locally and copied off-site.
# Requires: ~/.my.cnf for the backup DB user (see DEPLOYMENT.md), optional rclone remote "offsite".
set -euo pipefail
APP=${APP_DIR:-/var/www/seo-platform}
DEST=${BACKUP_DIR:-/var/backups/seo-platform}
DB=${DB_DATABASE:-seo_platform}
KEEP_DAILY=${KEEP_DAILY:-14}
KEEP_MONTHLY=${KEEP_MONTHLY:-12}
STAMP=$(date +%Y-%m-%d_%H%M)
mkdir -p "$DEST/daily" "$DEST/monthly"
umask 077

# 1) Consistent InnoDB dump without locking the app. Crawl page tables are large but re-creatable;
#    they are included so a restore keeps issue URLs and page explorer history.
mysqldump --single-transaction --quick --routines --triggers --no-tablespaces "$DB" | gzip -6 > "$DEST/daily/db-$STAMP.sql.gz"

# 2) Files that cannot be regenerated: report PDFs, branding logo, .env (contains APP_KEY needed to decrypt API secrets).
tar -czf "$DEST/daily/files-$STAMP.tar.gz" -C "$APP/shared" storage/app/private .env

# 3) Verify the archives are readable before rotating anything.
gzip -t "$DEST/daily/db-$STAMP.sql.gz"
tar -tzf "$DEST/daily/files-$STAMP.tar.gz" > /dev/null

# 4) Keep the first backup of each month as a monthly copy.
if [ "$(date +%d)" = "01" ]; then cp "$DEST/daily/db-$STAMP.sql.gz" "$DEST/daily/files-$STAMP.tar.gz" "$DEST/monthly/"; fi

# 5) Rotate.
find "$DEST/daily" -type f -mtime +"$KEEP_DAILY" -delete
for pattern in 'db-*.sql.gz' 'files-*.tar.gz'; do
  find "$DEST/monthly" -maxdepth 1 -type f -name "$pattern" -printf '%T@ %p\n' | sort -rn | tail -n +$((KEEP_MONTHLY + 1)) | cut -d' ' -f2- | xargs -r rm -f
done

# 6) Off-site copy (Backblaze B2, S3, Google Drive... configured with `rclone config` as remote "offsite").
if command -v rclone >/dev/null && rclone listremotes | grep -q '^offsite:'; then
  rclone copy "$DEST" offsite:intelliworkz-seo-backups --max-age 48h --transfers 2
fi
echo "$(date '+%F %T') backup ok: $(du -sh "$DEST/daily/db-$STAMP.sql.gz" | cut -f1) db, $(du -sh "$DEST/daily/files-$STAMP.tar.gz" | cut -f1) files"
