#!/bin/bash
# Automated PostgreSQL backup script
# Run via cron on the Supabase LXC: 0 */6 * * * /root/backup-db.sh
# Keeps 7 days of backups

BACKUP_DIR="/root/backups"
CONTAINER="supabase-db"
DB_NAME="postgres"
DB_USER="postgres"
KEEP_DAYS=7

mkdir -p "$BACKUP_DIR"

TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="$BACKUP_DIR/todo_backup_${TIMESTAMP}.sql.gz"

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

docker exec "$CONTAINER" pg_dump -U "$DB_USER" "$DB_NAME" --clean --if-exists | gzip > "$BACKUP_FILE"

if [ $? -eq 0 ] && [ -s "$BACKUP_FILE" ]; then
    echo "[$(date)] Backup saved: $BACKUP_FILE ($(du -h "$BACKUP_FILE" | cut -f1))"
else
    echo "[$(date)] ERROR: Backup failed!"
    rm -f "$BACKUP_FILE"
    exit 1
fi

# Remove backups older than KEEP_DAYS
find "$BACKUP_DIR" -name "todo_backup_*.sql.gz" -mtime +$KEEP_DAYS -delete
echo "[$(date)] Cleanup done. Current backups:"
ls -lh "$BACKUP_DIR"/todo_backup_*.sql.gz 2>/dev/null
