#!/bin/bash
# ============================================================================
# Script de Rollback - Avanzato
# ============================================================================
# Uso: bash ci/scripts/rollback.sh [numero]
#
# Restaura um backup anterior.
# ============================================================================

set -e

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

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}"

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

echo -e "${BLUE}============================================================${NC}"
echo -e "${BLUE}  Avanzato - Rollback${NC}"
echo -e "${BLUE}============================================================${NC}"
echo ""

# Listar backups disponiveis
echo "Backups disponiveis:"
echo ""

BACKUPS=()
i=1
for backup in $(ls -t "${BACKUP_PATH}"/*.tar.gz 2>/dev/null); do
    nome=$(basename "$backup")
    tamanho=$(du -h "$backup" | cut -f1)
    data=$(stat -c %y "$backup" | cut -d'.' -f1)
    printf "  ${GREEN}%2d.${NC} %s  (${tamanho})  %s\n" "$i" "$nome" "$data"
    BACKUPS+=("$backup")
    i=$((i + 1))
done

if [ ${#BACKUPS[@]} -eq 0 ]; then
    echo -e "${RED}Nenhum backup encontrado.${NC}"
    exit 1
fi

echo ""
read -p "Digite o numero do backup para restaurar: " NUM

if ! [[ "$NUM" =~ ^[0-9]+$ ]] || [ "$NUM" -lt 1 ] || [ "$NUM" -gt ${#BACKUPS[@]} ]; then
    echo -e "${RED}Numero invalido.${NC}"
    exit 1
fi

BACKUP="${BACKUPS[$((NUM - 1))]}"
echo ""
echo -e "Selecionado: ${YELLOW}$(basename "$BACKUP")${NC}"
echo "Destino: $DEPLOY_PATH"
read -p "Confirma? (s/N): " CONFIRM

if [ "$CONFIRM" != "s" ] && [ "$CONFIRM" != "S" ]; then
    echo "Cancelado."
    exit 0
fi

echo ""
echo -e "${YELLOW}Fazendo backup do estado atual antes do rollback...${NC}"
bash "$(dirname "$0")/backup.sh" "$AMBIENTE"

echo ""
echo -e "${YELLOW}Restaurando backup...${NC}"
rm -rf "${DEPLOY_PATH:?}"/*
tar -xzf "$BACKUP" -C "$(dirname "$DEPLOY_PATH")" --strip-components=1

echo -e "${GREEN}Rollback concluido!${NC}"
echo ""
echo "Verifique: ${DEPLOY_PATH}"
