#!/bin/bash

###############################################################################
# SCRIPT DE DEPLOY - WEBMoney Backend Laravel
# Servidor: 213.165.93.60
# Domínio: https://webmoney.cnxifly.com
# Versão: 1.0.0
###############################################################################

set -e  # Exit on error

# Colors para output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Configurações
SERVER_USER="root"
SERVER_HOST="213.165.93.60"
SERVER_PASSWORD="Master9354"
SERVER_PATH="/var/www/webmoney/backend"
LOCAL_PATH="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

echo -e "${GREEN}╔═══════════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║     WEBMoney Laravel - Deploy para Produção         ║${NC}"
echo -e "${GREEN}╚═══════════════════════════════════════════════════════╝${NC}"
echo ""

# Função para executar comandos no servidor remoto
remote_exec() {
    sshpass -p "$SERVER_PASSWORD" ssh -o StrictHostKeyChecking=no "$SERVER_USER@$SERVER_HOST" "$1"
}

# 1. Build local (se necessário)
echo -e "${YELLOW}[1/8]${NC} Verificando dependências locais..."
if [ ! -d "$LOCAL_PATH/vendor" ]; then
    echo "Instalando dependências do Composer..."
    composer install --no-dev --optimize-autoloader
fi

# 2. Sync arquivos via rsync
echo -e "${YELLOW}[2/8]${NC} Sincronizando arquivos para o servidor..."
sshpass -p "$SERVER_PASSWORD" rsync -avz --delete \
    --exclude='.git' \
    --exclude='node_modules' \
    --exclude='storage/logs/*' \
    --exclude='storage/framework/cache/*' \
    --exclude='storage/framework/sessions/*' \
    --exclude='storage/framework/views/*' \
    --exclude='.env' \
    --exclude='database/database.sqlite' \
    "$LOCAL_PATH/" "$SERVER_USER@$SERVER_HOST:$SERVER_PATH/"

echo -e "${GREEN}✓${NC} Arquivos sincronizados"

# 3. Copiar .env de produção
echo -e "${YELLOW}[3/8]${NC} Configurando .env de produção..."
sshpass -p "$SERVER_PASSWORD" ssh -o StrictHostKeyChecking=no "$SERVER_USER@$SERVER_HOST" \
    "cp $SERVER_PATH/.env.production $SERVER_PATH/.env"
echo -e "${GREEN}✓${NC} .env configurado"

# 4. Instalar dependências no servidor
echo -e "${YELLOW}[4/8]${NC} Instalando dependências no servidor..."
remote_exec "cd $SERVER_PATH && composer install --no-dev --optimize-autoloader"
echo -e "${GREEN}✓${NC} Dependências instaladas"

# 5. Ajustar permissões
echo -e "${YELLOW}[5/8]${NC} Ajustando permissões..."
remote_exec "chown -R www-data:www-data $SERVER_PATH/storage $SERVER_PATH/bootstrap/cache"
remote_exec "chmod -R 775 $SERVER_PATH/storage $SERVER_PATH/bootstrap/cache"
echo -e "${GREEN}✓${NC} Permissões ajustadas"

# 6. Executar migrações
echo -e "${YELLOW}[6/8]${NC} Executando migrações de banco de dados..."
remote_exec "cd $SERVER_PATH && php artisan migrate --force"
echo -e "${GREEN}✓${NC} Migrações executadas"

# 7. Cache e otimizações
echo -e "${YELLOW}[7/8]${NC} Otimizando aplicação..."
remote_exec "cd $SERVER_PATH && php artisan config:cache"
remote_exec "cd $SERVER_PATH && php artisan route:cache"
remote_exec "cd $SERVER_PATH && php artisan view:cache"
echo -e "${GREEN}✓${NC} Caches gerados"

# 8. Reload PHP-FPM
echo -e "${YELLOW}[8/8]${NC} Recarregando PHP-FPM..."
remote_exec "systemctl reload php8.4-fpm"
echo -e "${GREEN}✓${NC} PHP-FPM recarregado"

echo ""
echo -e "${GREEN}╔═══════════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║          ✓ DEPLOY CONCLUÍDO COM SUCESSO!             ║${NC}"
echo -e "${GREEN}╚═══════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "URL: ${GREEN}https://webmoney.cnxifly.com${NC}"
echo -e "API: ${GREEN}https://webmoney.cnxifly.com/api${NC}"
echo ""
echo -e "${YELLOW}Endpoints disponíveis:${NC}"
echo -e "  POST /api/register    - Registrar usuário"
echo -e "  POST /api/login       - Login"
echo -e "  POST /api/logout      - Logout (auth)"
echo -e "  GET  /api/me          - Dados do usuário (auth)"
echo ""
