#!/bin/bash
set -e

BACKUP_DIR="/backups"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_NAME="dyolink_backup_$TIMESTAMP"
BACKUP_FILE="$BACKUP_DIR/$BACKUP_NAME.sql.gz"

echo "[$(date)] Starting database backup: $BACKUP_NAME"

# Perform backup
pg_dumpall -U $POSTGRES_USER | gzip > $BACKUP_FILE

if [ $? -eq 0 ]; then
    BACKUP_SIZE=$(du -h $BACKUP_FILE | cut -f1)
    echo "[$(date)] ✅ Backup completed: $BACKUP_NAME ($BACKUP_SIZE)"
    
    # Keep only last 7 days of backups
    find $BACKUP_DIR -name "dyolink_backup_*.sql.gz" -mtime +7 -delete
    echo "[$(date)] Cleaned up backups older than 7 days"
else
    echo "[$(date)] ❌ Backup failed!"
    exit 1
fi