cat << 'EOF' > install_lb.sh
#!/bin/bash

# ==========================================
# INSTALADOR LOAD BALANCER (NGINX + MONITOR)
# ==========================================

# CORES
VERDE='\033[0;32m'
AZUL='\033[0;36m'
NC='\033[0m'

clear
echo -e "${AZUL}INICIANDO INSTALAÇÃO DO LOAD BALANCER...${NC}"
echo ""

# 1. DETECTAR IP AUTOMATICAMENTE
IP_VPS=$(curl -s ifconfig.me)
echo -e "${VERDE}IP Detectado:${NC} $IP_VPS"
echo ""

# 2. PERGUNTAS MANUAIS
echo "Digite o DNS que você apontou para esta VPS (LoadBalancer)."
echo "Exemplo: novo.topiptv.top"
read -p ">> DNS LB: " DOMINIO_LB

if [ -z "$DOMINIO_LB" ]; then DOMINIO_LB=$IP_VPS; fi

echo ""
echo "Digite a URL completa do seu Painel IPTV (Hospedagem)."
echo "Exemplo: http://turboflix.tvsbr.top"
read -p ">> URL Painel: " URL_PAINEL

# Extrai apenas o domínio do painel para usar no cabeçalho (Evita erro de user)
HOST_REAL=$(echo $URL_PAINEL | awk -F/ '{print $3}')

echo ""
echo -e "${AZUL}Instalando dependências (Nginx, PHP, VnStat)... Aguarde.${NC}"

# 3. INSTALAÇÃO DO SISTEMA
apt-get update -y > /dev/null 2>&1
apt-get install nginx php-fpm vnstat bc curl -y > /dev/null 2>&1

systemctl enable vnstat
systemctl start vnstat
systemctl stop nginx

# Detecta socket do PHP automaticamente
PHP_SOCK=$(find /run/php -name "php*-fpm.sock" | head -n 1)

# 4. CRIAR API DE MONITORAMENTO (STATUS)
mkdir -p /var/www/html
cat << 'PHP_EOF' > /var/www/html/status.php
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
error_reporting(0);

// CPU
$load = sys_getloadavg();
$cpu = $load[0] * 100;

// RAM
$free = shell_exec('free -m');
$free = (string)trim($free);
$arr = explode("\n", $free);
$mem = preg_split("/\s+/", $arr[1]);
$ram_total = $mem[1];
$ram_used = $mem[2];
$ram_perc = round(($ram_used / $ram_total) * 100);

// BANDA
$interface = shell_exec("ip route | grep default | awk '{print $5}'");
$interface = trim($interface);
$json = shell_exec("vnstat -i $interface --json m 1 2>/dev/null"); 
$data = json_decode($json, true);
$rx = 0; $tx = 0;
if (isset($data['interfaces'][0]['traffic']['month'][0])) {
    $rx = $data['interfaces'][0]['traffic']['month'][0]['rx'];
    $tx = $data['interfaces'][0]['traffic']['month'][0]['tx'];
}
$bw_gb = round(($rx + $tx) / 1073741824, 2);

echo json_encode([
    "cpu" => round($cpu, 1),
    "ram_total" => (int)$ram_total,
    "ram_used" => (int)$ram_used,
    "ram_percent" => $ram_perc,
    "bandwidth_used_gb" => $bw_gb
]);
?>
PHP_EOF
chmod 755 /var/www/html/status.php

# 5. CONFIGURAR NGINX (HÍBRIDO)
cat <<NGINX_EOF > /etc/nginx/sites-available/loadbalancer
server {
    listen 80;
    server_name $DOMINIO_LB $IP_VPS;

    # Otimizações Streaming
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    client_max_body_size 100M;

    # REGRA 1: MONITORAMENTO (Responde Localmente)
    location = /status.php {
        alias /var/www/html/status.php;
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:$PHP_SOCK;
    }

    # REGRA 2: TODO O RESTO (Manda para o Painel)
    location / {
        proxy_pass $URL_PAINEL;
        
        # O PULO DO GATO: Engana a hospedagem com o Host original
        proxy_set_header Host $HOST_REAL;
        
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header User-Agent \$http_user_agent;
        
        proxy_redirect off;
        proxy_buffering off;
    }
}
NGINX_EOF

# 6. ATIVAR E REINICIAR
rm -f /etc/nginx/sites-enabled/default
ln -s /etc/nginx/sites-available/loadbalancer /etc/nginx/sites-enabled/ 2>/dev/null

if nginx -t; then
    systemctl restart nginx
    echo ""
    echo -e "${VERDE}INSTALAÇÃO CONCLUÍDA COM SUCESSO!${NC}"
    echo "------------------------------------------------"
    echo "1. Vá no seu painel (Gerenciar Load Balancer)"
    echo "2. Adicione este servidor:"
    echo "   Nome: VPS 1"
    echo "   URL/DNS: $DOMINIO_LB"
    echo "   Porta: 80"
    echo "------------------------------------------------"
else
    echo -e "${VERMELHO}Erro na configuração do Nginx.${NC}"
fi
EOF
chmod +x install_lb.sh && ./install_lb.sh
