#!/bin/bash
# Script de backup diario de base de datos
# Ejecuta a las 2:00 AM

set -e

echo "[$(date '+%Y-%m-%d %H:%M:%S')] Iniciando backup de base de datos..."

# Variables de entorno
DB_HOST=${DB_HOST:-mysql}
DB_NAME=${DB_NAME:-usite_whatsapp_bot}
DB_USER=${DB_USER:-usite_whatsapp_user}
DB_PASS=${DB_PASS}

# Directorio de backups
BACKUP_DIR="/backups/database"
mkdir -p "$BACKUP_DIR"

# Nombre del archivo con timestamp
BACKUP_FILE="$BACKUP_DIR/backup_$(date +%Y%m%d_%H%M%S).sql.gz"

# Ejecutar backup comprimido
if mariadb-dump \
    --host="$DB_HOST" \
    --user="$DB_USER" \
    --password="$DB_PASS" \
    --single-transaction \
    --routines \
    --triggers \
    --events \
    "$DB_NAME" | gzip > "$BACKUP_FILE"; then
    
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] ✅ Backup creado exitosamente: $BACKUP_FILE"
    
    # Obtener tamaño del backup
    SIZE=$(du -h "$BACKUP_FILE" | cut -f1)
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Tamaño del backup: $SIZE"
    
    # Eliminar backups antiguos (más de 7 días)
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Limpiando backups antiguos..."
    find "$BACKUP_DIR" -name "backup_*.sql.gz" -type f -mtime +7 -delete
    
    # Contar backups restantes
    BACKUP_COUNT=$(find "$BACKUP_DIR" -name "backup_*.sql.gz" -type f | wc -l)
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Backups disponibles: $BACKUP_COUNT"
    
else
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] ❌ Error al crear backup"
    exit 1
fi

echo "[$(date '+%Y-%m-%d %H:%M:%S')] Backup completado"
