#!/bin/bash
# ============================================================================
# Script de Deploy - Avanzato
# ============================================================================
# Uso: bash scripts/deploy.sh [ambiente]
#
# Ambientes:
#   production (padrao) - Deploy para producao
#   staging             - Deploy para staging
#
# EXEMPLO:
#   bash scripts/deploy.sh production
#   bash scripts/deploy.sh staging
# ============================================================================

set -e

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

# Diretorios
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
DIST_DIR="${PROJECT_DIR}/dist"

# Ambiente
ENVIRONMENT="${1:-production}"

# Configuracoes (EDITAR ESTAS VARIAVEIS)
# ============================================
SSH_HOST="${SSH_HOST:-SEU_SERVIDOR_AQUI}"        # Ex: 201.45.120.30
SSH_USER="${SSH_USER:-root}"                      # Ex: root
SSH_PORT="${SSH_PORT:-22}"
DEPLOY_PATH="${DEPLOY_PATH:-/var/www/avanzato}"   # Caminho no servidor
# ============================================

echo "=========================================="
echo -e "  ${BLUE}Avanzato - Deploy${NC}"
echo "=========================================="
echo ""
echo -e "Ambiente: ${YELLOW}${ENVIRONMENT}${NC}"
echo ""

# Verificar se o dist existe
if [ ! -d "$DIST_DIR" ]; then
    echo -e "${RED}Erro: Pasta dist/ nao encontrada!${NC}"
    echo "Execute primeiro: npm run build"
    exit 1
fi

# Verificar se o diretorio do projeto existe no servidor
echo -e "${BLUE}[1/6]${NC} Verificando conexao com servidor..."
if ! ssh -p "$SSH_PORT" -o ConnectTimeout=10 "${SSH_USER}@${SSH_HOST}" "echo 'Conectado!'" 2>/dev/null; then
    echo -e "${RED}Erro: Nao foi possivel conectar ao servidor.${NC}"
    echo ""
    echo "Verifique:"
    echo "  1. Se o SSH_HOST esta correto"
    echo "  2. Se a chave SSH esta configurada"
    echo "  3. Se o servidor esta online"
    echo ""
    echo "Para configurar SSH:"
    echo "  ssh-copy-id -i ~/.ssh/id_ed25519.pub ${SSH_USER}@${SSH_HOST}"
    exit 1
fi
echo -e "${GREEN}OK${NC} - Servidor acessivel"
echo ""

# Preservar assets customizados
echo -e "${BLUE}[2/6]${NC} Preservando assets customizados..."
if [ -d "${PROJECT_DIR}/custom-assets" ]; then
    bash "${SCRIPT_DIR}/preserve-assets.sh" "$DIST_DIR"
else
    echo -e "${YELLOW}Nenhum asset customizado encontrado.${NC}"
fi
echo ""

# Configurar robots.txt e anti-indexacao conforme ambiente
echo -e "${BLUE}[3/6]${NC} Configurando anti-indexacao para ambiente: ${ENVIRONMENT}..."
if [ "$ENVIRONMENT" == "production" ]; then
    # Producao: permitir indexacao
    cp "${PROJECT_DIR}/public/robots-producao.txt" "${DIST_DIR}/robots.txt"
    echo -e "${GREEN}OK${NC} - robots.txt configurado para PRODUCAO (allow)"
else
    # Homolog/Staging: bloquear indexacao
    cp "${PROJECT_DIR}/public/robots.txt" "${DIST_DIR}/robots.txt"
    echo -e "${YELLOW}ATENCAO${NC} - robots.txt configurado para HOMOLOGACAO (disallow all)"
fi
echo ""

# Fazer backup do site atual (opcional)
echo -e "${BLUE}[4/6]${NC} Criando backup..."
BACKUP_DIR="backup-$(date +%Y%m%d-%H%M%S)"
ssh -p "$SSH_PORT" "${SSH_USER}@${SSH_HOST}" "
    if [ -d '${DEPLOY_PATH}' ]; then
        mkdir -p '${DEPLOY_PATH}/backups'
        cp -r '${DEPLOY_PATH}' '${DEPLOY_PATH}/backups/${BACKUP_DIR}' 2>/dev/null || true
        echo 'Backup criado: backups/${BACKUP_DIR}'
    fi
" 2>/dev/null || echo -e "${YELLOW}Backup ignorado (primeiro deploy).${NC}"
echo ""

# Deploy via rsync
echo -e "${BLUE}[5/6]${NC} Enviando arquivos para servidor..."
rsync -avz --delete \
    -e "ssh -p ${SSH_PORT}" \
    --exclude='backups' \
    "$DIST_DIR/" \
    "${SSH_USER}@${SSH_HOST}:${DEPLOY_PATH}/"

echo ""
echo -e "${GREEN}OK${NC} - Arquivos enviados!"
echo ""

# Limpar cache (se necessario)
echo -e "${BLUE}[6/6]${NC} Finalizando..."
# Aqui voce pode adicionar comandos especificos do servidor
# ssh -p "$SSH_PORT" "${SSH_USER}@${SSH_HOST}" "sudo systemctl restart nginx" 2>/dev/null || true

echo ""
echo "=========================================="
echo -e "${GREEN}Deploy concluido com sucesso!${NC}"
echo "=========================================="
echo ""
echo -e "Ambiente: ${YELLOW}${ENVIRONMENT}${NC}"
echo -e "Servidor: ${SSH_USER}@${SSH_HOST}:${DEPLOY_PATH}"
echo ""
echo "Verifique o site:"
echo "  https://avanzato.com.br"
echo ""
