#!/bin/bash

# ==========================================
# CONFIGURAÇÕES FIXAS DO BANCO DE DADOS
# ==========================================
DB_NAME="officextream"
DB_USER="user_officextream"
DB_PASS="pass_officextream"
# ==========================================

# CORES
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

clear
echo -e "${GREEN}=================================================${NC}"
echo -e "${GREEN}   INSTALADOR LOAD BALANCE (DADOS FIXOS)         ${NC}"
echo -e "${GREEN}=================================================${NC}"
echo ""

# 1. VERIFICA ROOT
if [ "$EUID" -ne 0 ]; then
  echo -e "${RED}Execute como root! (sudo su)${NC}"
  exit
fi

# 2. PEDE APENAS O IP (O RESTO JÁ ESTÁ FIXO)
echo -e "${YELLOW}Configuração de conexão com o Painel Master:${NC}"
read -p "Digite o IP da VPS Master: " MASTER_IP

if [ -z "$MASTER_IP" ]; then
    echo -e "${RED}IP inválido! Tente novamente.${NC}"
    exit
fi

echo ""
echo -e "${YELLOW}Iniciando instalação automática...${NC}"
sleep 2

# 3. INSTALA PACOTES
apt-get update -y
# Instala Apache, PHP, MySQL-Client e FFMPEG
apt-get install -y apache2 php libapache2-mod-php php-mysql php-curl ffmpeg unzip

# Habilita módulos essenciais
a2enmod rewrite
systemctl restart apache2

# 4. LIMPEZA E ESTRUTURA
rm -rf /var/www/html/index.html
mkdir -p /var/www/html/includes

# 5. GERA O ARQUIVO DE CONEXÃO (db.php)
echo -e "${GREEN}>>> Gerando arquivo de conexão...${NC}"

cat <<EOF > /var/www/html/includes/db.php
<?php
// includes/db.php - CONFIGURAÇÃO AUTOMÁTICA
\$host = '$MASTER_IP';
\$dbname = '$DB_NAME';
\$username = '$DB_USER';
\$password = '$DB_PASS';

try {
    \$pdo = new PDO("mysql:host=\$host;dbname=\$dbname;charset=utf8", \$username, \$password);
    \$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException \$e) {
    die("Erro de Conexão com o Master ($MASTER_IP): " . \$e->getMessage());
}
?>
EOF

# 6. GERA O ARQUIVO DE STREAM (stream.php)
echo -e "${GREEN}>>> Criando sistema de transmissão FFMPEG...${NC}"

cat << 'EOF' > /var/www/html/stream.php
<?php
// stream.php - REPASSADOR DE LOAD BALANCE
set_time_limit(0);
error_reporting(0);
ini_set('display_errors', 0);

require_once 'includes/db.php';

$username = $_GET['username'] ?? '';
$password = $_GET['password'] ?? '';
$stream_id = (int)($_GET['stream'] ?? 0);
$type = $_GET['type'] ?? 'live'; 

// Valida usuário no Banco do Master
$stmt = $pdo->prepare("SELECT id, username, active FROM users WHERE username = ? AND password = ? LIMIT 1");
$stmt->execute([$username, $password]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user || $user['active'] == 0) { http_response_code(403); exit; }

// Busca o Link do conteúdo
$real_link = "";
if ($type == 'live') {
    $r = $pdo->query("SELECT stream_url FROM channels WHERE id=$stream_id")->fetch(PDO::FETCH_ASSOC);
    if($r) $real_link = $r['stream_url'];
} elseif ($type == 'movie') {
    $r = $pdo->query("SELECT stream_url FROM movies WHERE id=$stream_id")->fetch(PDO::FETCH_ASSOC);
    if($r) $real_link = $r['stream_url'];
} elseif ($type == 'series') {
    $r = $pdo->query("SELECT e.stream_url FROM episodes e JOIN seasons s ON e.season_id=s.id WHERE e.id=$stream_id")->fetch(PDO::FETCH_ASSOC);
    if($r) $real_link = $r['stream_url'];
}

if (empty($real_link)) { http_response_code(404); exit; }

// Inicia Transmissão (FFMPEG)
$ffmpeg_bin = '/usr/bin/ffmpeg'; 
$ua_fake = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";

header('Content-Type: video/mp2t');

// Comando Otimizado: Reconecta sozinho e usa buffer de 1MB para estabilidade
$cmd = "$ffmpeg_bin -reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5 -user_agent \"$ua_fake\" -i \"$real_link\" -c copy -f mpegts -bufsize 1024k pipe:1 2>/dev/null";

$handle = popen($cmd, 'r');
if ($handle) {
    while (!feof($handle)) {
        if (connection_aborted()) break;
        echo fread($handle, 16384);
        if (ob_get_length() > 0) ob_flush();
        flush();
    }
    pclose($handle);
}
exit;
?>
EOF

# 7. PERMISSÕES
chown -R www-data:www-data /var/www/html
chmod -R 755 /var/www/html

# 8. FIM
PUBLIC_IP=$(curl -s ifconfig.me)
echo ""
echo -e "${GREEN}INSTALAÇÃO CONCLUÍDA!${NC}"
echo "------------------------------------------------"
echo "Dados cadastrados:"
echo "Banco: $DB_NAME"
echo "User:  $DB_USER"
echo "Senha: $DB_PASS"
echo "Master IP: $MASTER_IP"
echo "------------------------------------------------"
echo ""
echo -e "${YELLOW}Para adicionar este servidor no painel use:${NC}"
echo "URL: http://$PUBLIC_IP"
echo ""