#!/bin/bash
# CRM Clinicas — Daily PostgreSQL Backup Script
# Runs via cron: 0 3 * * * /root/CrmClinicas/scripts/backup.sh >> /root/CrmClinicas/backups/backup.log 2>&1

set -euo pipefail

BACKUP_DIR="/root/CrmClinicas/backups"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
KEEP_DAYS=7

mkdir -p "$BACKUP_DIR"

echo "[$(date)] Starting backup..."

# Dump PostgreSQL
docker exec docker-db-1 pg_dump \
  -U supabase_admin \
  -d postgres \
  --format=custom \
  --compress=9 \
  -f /tmp/backup_${TIMESTAMP}.dump 2>&1

# Copy dump from container
docker cp docker-db-1:/tmp/backup_${TIMESTAMP}.dump \
  "$BACKUP_DIR/db_${TIMESTAMP}.dump"

# Clean up temp file in container
docker exec docker-db-1 rm -f /tmp/backup_${TIMESTAMP}.dump

# Remove old backups (keep last N days)
find "$BACKUP_DIR" -name "db_*.dump" -mtime +${KEEP_DAYS} -delete 2>/dev/null || true

# Show backup size
BACKUP_SIZE=$(du -h "$BACKUP_DIR/db_${TIMESTAMP}.dump" | cut -f1)
echo "[$(date)] Backup completed: db_${TIMESTAMP}.dump (${BACKUP_SIZE})"

# Count remaining backups
BACKUP_COUNT=$(ls -1 "$BACKUP_DIR"/db_*.dump 2>/dev/null | wc -l)
echo "[$(date)] Total backups retained: ${BACKUP_COUNT}"
