#!/bin/bash # Fix NGINX Load Balancer SSL Configuration # Corrige problemas de SSL do NGINX Load Balancer set -e LOADBALANCER_IP="141.148.162.114" SSH_USER="ubuntu" DOMAIN="bcards.site" # Cores para output RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' BLUE='\033[0;34m' NC='\033[0m' log() { echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')] $1${NC}" } error() { echo -e "${RED}[ERROR] $1${NC}" exit 1 } warn() { echo -e "${YELLOW}[WARNING] $1${NC}" } info() { echo -e "${BLUE}[INFO] $1${NC}" } run_remote() { local server_ip=$1 local command=$2 ssh -o StrictHostKeyChecking=no ${SSH_USER}@${server_ip} "$command" } # Etapa 1: Configurar NGINX apenas com HTTP fix_nginx_http() { log "Configurando NGINX apenas com HTTP..." # Copiar configuração HTTP scp nginx/nginx-loadbalancer-http.conf ${SSH_USER}@${LOADBALANCER_IP}:/tmp/ run_remote $LOADBALANCER_IP " # Parar NGINX sudo systemctl stop nginx || true # Backup da configuração atual sudo mkdir -p /etc/nginx/backup sudo cp /etc/nginx/sites-available/bcards /etc/nginx/backup/bcards-ssl.bak 2>/dev/null || true # Instalar configuração HTTP sudo cp /tmp/nginx-loadbalancer-http.conf /etc/nginx/sites-available/bcards # Criar diretório para ACME challenge sudo mkdir -p /var/www/html sudo chown www-data:www-data /var/www/html # Testar configuração sudo nginx -t # Iniciar NGINX sudo systemctl start nginx sudo systemctl enable nginx " info "✓ NGINX configurado apenas com HTTP" } # Etapa 2: Testar se o domínio está acessível test_domain_connectivity() { log "Testando conectividade do domínio..." # Primeiro, verificar se os backends estão rodando info "Verificando se os backends estão rodando..." for backend in "129.153.123.92:8080" "129.146.116.218:8080"; do if curl -s --connect-timeout 5 "http://$backend/health" >/dev/null 2>&1; then info "✓ Backend $backend está respondendo" else warn "Backend $backend não está respondendo" fi done # Testar conectividade local do load balancer info "Testando NGINX localmente no load balancer..." run_remote $LOADBALANCER_IP " # Testar localmente curl -s -o /dev/null -w 'Status: %{http_code}\n' http://localhost/health || echo 'Local test failed' " # Aguardar propagação DNS info "Aguardando 30 segundos para propagação..." sleep 30 # Testar acesso externo info "Testando acesso externo ao domínio..." local status=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 10 "http://$DOMAIN/health" 2>/dev/null || echo "000") if [ "$status" = "200" ]; then info "✓ Domínio $DOMAIN está acessível" return 0 else warn "Domínio $DOMAIN não está acessível (status: $status)" # Diagnóstico adicional info "Executando diagnóstico..." nslookup $DOMAIN || true info "Tentando ping..." ping -c 3 $DOMAIN || true return 1 fi } # Etapa 3: Configurar SSL (apenas se domínio estiver acessível) setup_ssl_proper() { log "Configurando SSL com Let's Encrypt..." run_remote $LOADBALANCER_IP " # Obter certificado SSL apenas para domínio principal (sem www) sudo certbot certonly --webroot -w /var/www/html -d $DOMAIN --non-interactive --agree-tos --email admin@$DOMAIN # Verificar se certificado foi criado if [ ! -f /etc/letsencrypt/live/$DOMAIN/fullchain.pem ]; then echo 'Certificado não foi criado!' exit 1 fi " # Agora configurar NGINX com SSL scp nginx/nginx-loadbalancer.conf ${SSH_USER}@${LOADBALANCER_IP}:/tmp/ run_remote $LOADBALANCER_IP " # Atualizar configuração para SSL (remover www do server_name) sed -i 's/server_name bcards.site www.bcards.site;/server_name bcards.site;/g' /tmp/nginx-loadbalancer.conf # Aplicar configuração SSL sudo cp /tmp/nginx-loadbalancer.conf /etc/nginx/sites-available/bcards # Testar configuração sudo nginx -t # Reload NGINX sudo systemctl reload nginx # Configurar renovação automática (apenas se não existir) if ! crontab -l 2>/dev/null | grep -q certbot; then echo '0 2 * * * certbot renew --quiet && systemctl reload nginx' | sudo crontab - fi " info "✓ SSL configurado com sucesso" } # Função principal main() { log "Corrigindo configuração NGINX SSL para BCards..." # Etapa 1: Configurar HTTP primeiro fix_nginx_http # Etapa 2: Testar conectividade if test_domain_connectivity; then # Etapa 3: Se domínio estiver acessível, configurar SSL if [[ "$1" == "--ssl" ]]; then setup_ssl_proper info "Acesso: https://$DOMAIN" else info "SSL não configurado. Use --ssl para configurar." info "Acesso: http://$DOMAIN" fi else warn "Domínio não está acessível. Verifique:" warn "1. DNS está apontando para $LOADBALANCER_IP" warn "2. Backends estão rodando nas portas 8080" warn "3. Firewall permite tráfego HTTP (porta 80)" info "Por enquanto, acesso apenas local: http://$LOADBALANCER_IP" fi log "Correção concluída!" } # Mostrar ajuda if [[ "$1" == "--help" || "$1" == "-h" ]]; then echo "Fix NGINX Load Balancer SSL Configuration" echo "" echo "Usage: $0 [OPTIONS]" echo "" echo "OPTIONS:" echo " --ssl Configurar SSL após verificar conectividade" echo " --help Mostrar esta ajuda" echo "" echo "Este script:" echo "1. Configura NGINX apenas com HTTP primeiro" echo "2. Testa se o domínio está acessível" echo "3. Só configura SSL se domínio estiver funcionando" echo "" exit 0 fi # Executar função principal main "$@"