#!/bin/bash
# ============================================================================
# Script de Backup - Avanzato
# ============================================================================
# Uso: bash ci/scripts/backup.sh [ambiente]
#
# Faz backup manual do site.
# ============================================================================

set -e

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

# Carregar config
CONFIG_FILE="/var/ci/config.env"
if [ -f "$CONFIG_FILE" ]; then
    source "$CONFIG_FILE"
fi

DEPLOY_PATH="${DEPLOY_PATH:-/var/www/avanzato}"
BACKUP_PATH="${BACKUP_PATH:-/var/ci/backups}"
AMBIENTE="${1:-production}"

# Determinar diretorio
if [ "$AMBIENTE" = "staging" ]; then
    DEPLOY_PATH="${STAGING_PATH:-$DEPLOY_PATH-staging}"
fi

BACKUP_NAME="backup-$(date +%Y%m%d-%H%M%S)"

mkdir -p "$BACKUP_PATH"

if [ ! -d "$DEPLOY_PATH" ] || [ ! "$(ls -A "$DEPLOY_PATH" 2>/dev/null)" ]; then
    echo -e "${RED}Nada para fazer backup.${NC}"
    exit 1
fi

echo -e "${GREEN}Criando backup...${NC}"
echo "Origem: $DEPLOY_PATH"
echo "Destino: $BACKUP_PATH/${BACKUP_NAME}.tar.gz"

tar -czf "${BACKUP_PATH}/${BACKUP_NAME}.tar.gz" \
    -C "$(dirname "$DEPLOY_PATH")" \
    --exclude="backups" \
    "$(basename "$DEPLOY_PATH")"

echo -e "${GREEN}Backup criado: ${BACKUP_NAME}.tar.gz${NC}"

# Limpar backups antigos
MAX_BACKUPS="${MAX_BACKUPS:-10}"
echo "Limpando backups antigos (manter $MAX_BACKUPS)..."
ls -t "${BACKUP_PATH}"/*.tar.gz 2>/dev/null | tail -n +$((MAX_BACKUPS + 1)) | xargs -r rm -f
echo -e "${GREEN}Concluido!${NC}"
