#!/bin/bash
# Configuração de HTTPS com Let's Encrypt
# Domínio: gestor.jf.eng.br

set -e

DOMAIN="gestor.jf.eng.br"
EMAIL="admin@jf.eng.br"  # Altere para seu email

echo "🔒 =========================================="
echo "   Configuração HTTPS - Let's Encrypt"
echo "   Domínio: $DOMAIN"
echo "=========================================="
echo ""

# Verificar se está rodando como root
if [ "$EUID" -ne 0 ]; then 
    echo "❌ Execute como root: sudo bash $0"
    exit 1
fi

# 1. INSTALAR CERTBOT
echo "📦 [1/5] Instalando Certbot..."
echo "---"

if ! command -v certbot >/dev/null; then
    apt-get update
    apt-get install -y certbot python3-certbot-nginx
    echo "✅ Certbot instalado"
else
    echo "✅ Certbot já instalado"
fi
echo ""

# 2. VERIFICAR DNS
echo "🌐 [2/5] Verificando DNS..."
echo "---"
echo "Resolvendo $DOMAIN:"
DNS_IP=$(nslookup $DOMAIN | grep -A1 "Name:" | tail -1 | awk '{print $2}')
echo "DNS aponta para: $DNS_IP"

# Pegar IP do servidor
SERVER_IP=$(curl -s ifconfig.me)
echo "IP do servidor: $SERVER_IP"

if [ "$DNS_IP" != "$SERVER_IP" ]; then
    echo "⚠️ AVISO: DNS não aponta para este servidor!"
    echo "Certifique-se de que $DOMAIN aponta para $SERVER_IP"
    read -p "Continuar mesmo assim? (s/n): " -n 1 -r
    echo ""
    if [[ ! $REPLY =~ ^[Ss]$ ]]; then
        exit 0
    fi
fi
echo ""

# 3. OBTER CERTIFICADO
echo "🔐 [3/5] Obtendo certificado SSL..."
echo "---"

# Parar Nginx temporariamente para o Certbot usar porta 80
systemctl stop nginx

# Obter certificado
certbot certonly --standalone \
    --non-interactive \
    --agree-tos \
    --email "$EMAIL" \
    -d "$DOMAIN"

if [ $? -eq 0 ]; then
    echo "✅ Certificado SSL obtido com sucesso!"
else
    echo "❌ Erro ao obter certificado SSL"
    systemctl start nginx
    exit 1
fi
echo ""

# 4. CONFIGURAR NGINX PARA HTTPS
echo "🌐 [4/5] Configurando Nginx para HTTPS..."
echo "---"

cat > /etc/nginx/sites-available/gestorstream << EOF
# Redirecionar HTTP para HTTPS
server {
    listen 80;
    listen [::]:80;
    server_name $DOMAIN;
    
    # Redirecionar tudo para HTTPS
    return 301 https://\$server_name\$request_uri;
}

# HTTPS
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name $DOMAIN;

    # Certificados SSL
    ssl_certificate /etc/letsencrypt/live/$DOMAIN/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/$DOMAIN/privkey.pem;
    
    # Configurações SSL (modernas e seguras)
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
    ssl_prefer_server_ciphers off;
    
    # HSTS (force HTTPS for 1 year)
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    
    # Other security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;

    root /var/www/gestorstream/frontend/dist;
    index index.html;

    # Logs
    access_log /var/log/nginx/gestorstream-access.log;
    error_log /var/log/nginx/gestorstream-error.log;

    client_max_body_size 100M;

    # Frontend - SPA (arquivos estáticos)
    location / {
        try_files \$uri \$uri/ /index.html;
        # Cache control para index.html (não cachear para pegar novas versões)
        add_header Cache-Control "no-cache, no-store, must-revalidate" always;
    }

    # Arquivos estáticos do frontend (JS, CSS, imagens, fontes) - cache longo
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot|map)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
        # Permitir CORS se necessário
        add_header Access-Control-Allow-Origin *;
    }

    # Backend API - porta 8000
    location /api {
        proxy_pass http://127.0.0.1:8000;
        proxy_http_version 1.1;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }

    # Storage (uploads)
    location /storage {
        alias /var/www/gestorstream/backend/storage/app/public;
        try_files \$uri \$uri/ =404;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
}
EOF

echo "✅ Configuração Nginx criada"
echo ""

# 5. ATIVAR E REINICIAR
echo "🔄 [5/5] Ativando configuração..."
echo "---"

# Ativar site
rm -f /etc/nginx/sites-enabled/default
rm -f /etc/nginx/sites-enabled/gestorstream
ln -sf /etc/nginx/sites-available/gestorstream /etc/nginx/sites-enabled/gestorstream

# Testar
nginx -t

if [ $? -eq 0 ]; then
    systemctl start nginx
    echo "✅ Nginx reiniciado com HTTPS"
else
    echo "❌ Erro na configuração do Nginx!"
    exit 1
fi

# Configurar renovação automática
if ! crontab -l 2>/dev/null | grep -q "certbot renew"; then
    (crontab -l 2>/dev/null; echo "0 3 * * * certbot renew --quiet --post-hook 'systemctl reload nginx'") | crontab -
    echo "✅ Renovação automática configurada (diária às 3h)"
fi

echo ""
echo "🎉 =========================================="
echo "   HTTPS CONFIGURADO COM SUCESSO!"
echo "=========================================="
echo ""
echo "🔒 Acesse agora: https://$DOMAIN"
echo ""
echo "📝 Notas importantes:"
echo "   - HTTP (porta 80) redireciona automaticamente para HTTPS"
echo "   - Acesso direto por IP:porta está bloqueado"
echo "   - Certificado renova automaticamente a cada 90 dias"
echo ""
echo "🔍 Testar certificado:"
echo "   openssl s_client -connect $DOMAIN:443 -servername $DOMAIN"
echo ""
echo "📊 Status do certificado:"
certbot certificates
