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

echo "🚀 Iniciando instalação do Pixeldrain VOD Manager..."

# 1. Atualizar sistema e instalar dependências
sudo apt update && sudo apt upgrade -y
sudo apt install python3 python3-pip python3-venv ffmpeg curl -y

# 2. Instalar yt-dlp
sudo curl -L https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp -o /usr/local/bin/yt-dlp
sudo chmod a+rx /usr/local/bin/yt-dlp

# 3. Instalar bibliotecas Python
pip3 install flask flask-login requests

# 4. Criar estrutura
mkdir -p templates

# 5. Criar config.json
cat << 'EOC' > config.json
{"usuario": "admin", "senha": "123", "api_key": ""}
EOC

# 6. Criar app.py
cat << 'EOC' > app.py
from flask import Flask, render_template, request, jsonify, redirect, url_for
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user
import threading, os, subprocess, json, re

app = Flask(__name__)
app.secret_key = 'vps_secret_key_9988'
CONFIG_FILE = 'config.json'

def carregar_config():
    if not os.path.exists(CONFIG_FILE):
        default = {"usuario": "admin", "senha": "123", "api_key": ""}
        with open(CONFIG_FILE, 'w') as f: json.dump(default, f)
    with open(CONFIG_FILE, 'r') as f: return json.load(f)

def salvar_config(nova_config):
    with open(CONFIG_FILE, 'w') as f: json.dump(nova_config, f)

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'

class User(UserMixin):
    def __init__(self, id): self.id = id

@login_manager.user_loader
def load_user(user_id): return User(user_id)

fila, historico = [], []
processando = False

def limpar_nome(nome):
    nome = re.sub(r'[()\[\]]', '', nome)
    nome = nome.replace(' ', '_')
    if not nome.lower().endswith('.mp4'): nome += ".mp4"
    return nome

def processar_fila():
    global processando
    processando = True
    while fila:
        conf = carregar_config()
        item = fila[0]
        nome_limpo = limpar_nome(item['nome'])
        try:
            item['status'] = "Baixando..."
            subprocess.run(['yt-dlp', '-o', nome_limpo, item['link']], check=True)
            item['status'] = "Enviando..."
            cmd = ['curl', '-X', 'POST', '-u', f':{conf["api_key"]}', '-F', f'file=@{nome_limpo}', 'https://pixeldrain.com/api/file']
            result = subprocess.run(cmd, capture_output=True, text=True)
            res_json = json.loads(result.stdout)
            if res_json.get("success"):
                link_final = f"https://pixeldrain.com/api/file/{res_json['id']}"
                historico.insert(0, {"nome": nome_limpo, "link": link_final})
                item['status'] = "Concluido"
            else:
                raise Exception("Erro Pixeldrain")
            if os.path.exists(nome_limpo): os.remove(nome_limpo)
        except Exception as e:
            item['status'] = "Erro!"
            historico.insert(0, {"nome": nome_limpo, "link": "Falha no link/upload"})
        fila.pop(0)
    processando = False

@app.route('/login', methods=['GET', 'POST'])
def login():
    conf = carregar_config()
    if request.method == 'POST':
        if request.form['u'] == conf['usuario'] and request.form['p'] == conf['senha']:
            login_user(User(1))
            return redirect(url_for('index'))
    return render_template('login.html')

@app.route('/')
@login_required
def index(): return render_template('index.html', config=carregar_config())

@app.route('/save_config', methods=['POST'])
@login_required
def save_config_route():
    salvar_config({"usuario": request.form.get('usuario'), "senha": request.form.get('senha'), "api_key": request.form.get('api_key')})
    return jsonify({"status": "ok"})

@app.route('/status')
@login_required
def status(): return jsonify({"fila": fila, "historico": historico})

@app.route('/add', methods=['POST'])
@login_required
def add():
    nome, link = request.form.get('nome'), request.form.get('link')
    if nome and link:
        fila.append({"nome": nome, "link": link, "status": "Na fila"})
        if not processando: threading.Thread(target=processar_fila).start()
    return jsonify({"status": "ok"})

@app.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('login'))

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=3000)
EOC

# 7. Criar HTMLs
cat << 'EOC' > templates/login.html
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login | VOD Manager</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <style>
        body { background: #0f0f13; height: 100vh; display: flex; align-items: center; justify-content: center; padding: 20px; }
        .login-card { background: #1a1a24; padding: 30px; border-radius: 20px; border: 1px solid #333; width: 100%; max-width: 380px; }
        .btn-primary { background: linear-gradient(90deg, #6200ee, #7c4dff); border: none; padding: 15px; font-weight: bold; border-radius: 12px; color:white; }
        input { background: #282833 !important; border: 1px solid #3f3f4d !important; color: white !important; padding: 15px !important; margin-bottom: 20px; }
    </style>
</head>
<body>
    <div class="login-card text-center text-white">
        <h3 class="mb-4">ACESSO VOD</h3>
        <form method="post">
            <input type="text" name="u" class="form-control" placeholder="Usuário" required>
            <input type="password" name="p" class="form-control" placeholder="Senha" required>
            <button type="submit" class="btn btn-primary w-100">ENTRAR</button>
        </form>
    </div>
</body>
</html>
EOC

cat << 'EOC' > templates/index.html
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>VOD Manager Pro</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { background: #0f0f13; color: #e1e1e6; font-family: sans-serif; }
        .navbar { background: linear-gradient(90deg, #6200ee, #03dac6); }
        .card { background: #1a1a24; border: none; border-radius: 15px; margin-bottom: 15px; }
        .form-control { background: #282833; border: 1px solid #3f3f4d; color: white; }
        .link-result { background: #0f0f13; border: 1px dashed #03dac6; padding: 12px; border-radius: 8px; color: #03dac6; word-break: break-all; font-family: monospace; }
        .btn-settings { background: rgba(255,255,255,0.15); border: none; color: white; border-radius: 12px; width: 45px; height: 45px; }
        .modal-content { background: #1a1a24; color: white; border-radius: 20px; }
    </style>
</head>
<body>
<nav class="navbar navbar-dark p-2 sticky-top">
    <div class="container d-flex justify-content-between align-items-center">
        <span class="navbar-brand h1 mb-0">VOD Manager</span>
        <div>
            <button class="btn-settings" data-bs-toggle="modal" data-bs-target="#settingsModal"><i class="fas fa-cog"></i></button>
            <a href="/logout" class="ms-2 text-white px-2"><i class="fas fa-sign-out-alt fa-lg"></i></a>
        </div>
    </div>
</nav>
<div class="container mt-3">
    <div class="row">
        <div class="col-lg-5">
            <div class="card p-3">
                <h5 class="text-info"><i class="fas fa-plus-circle me-2"></i> Novo VOD</h5>
                <input type="text" id="nome" class="form-control mt-3" placeholder="Nome do Filme">
                <input type="text" id="link" class="form-control mt-2" placeholder="Link de Origem">
                <button onclick="add()" class="btn btn-primary w-100 mt-3 fw-bold">PROCESSAR AGORA</button>
            </div>
            <div class="card p-3">
                <h6 class="text-secondary small fw-bold">FILA ATIVA</h6>
                <div id="fila"></div>
            </div>
        </div>
        <div class="col-lg-7">
            <h5 class="text-success px-1">Links Prontos (XUI)</h5>
            <div id="historico"></div>
        </div>
    </div>
</div>
<div class="modal fade" id="settingsModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0">
            <div class="modal-body p-4 text-center">
                <h5>Configurações</h5>
                <input type="text" id="conf_user" class="form-control mt-3" value="{{ config.usuario }}" placeholder="Usuário">
                <input type="password" id="conf_pass" class="form-control mt-2" value="{{ config.senha }}" placeholder="Senha">
                <input type="text" id="conf_api" class="form-control mt-2" value="{{ config.api_key }}" placeholder="Pixeldrain API Key">
                <button onclick="saveConfig()" class="btn btn-success w-100 mt-3">SALVAR</button>
            </div>
        </div>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function add() {
        const fd = new FormData();
        fd.append('nome', document.getElementById('nome').value);
        fd.append('link', document.getElementById('link').value);
        fetch('/add', {method: 'POST', body: fd}).then(() => {
            document.getElementById('nome').value = ''; document.getElementById('link').value = ''; update();
        });
    }
    function saveConfig() {
        const fd = new FormData();
        fd.append('usuario', document.getElementById('conf_user').value);
        fd.append('senha', document.getElementById('conf_pass').value);
        fd.append('api_key', document.getElementById('conf_api').value);
        fetch('/save_config', {method: 'POST', body: fd}).then(() => { alert('Salvo!'); location.reload(); });
    }
    function update() {
        fetch('/status').then(r => r.json()).then(data => {
            let hFila = '', hHist = '';
            data.fila.forEach(i => { hFila += `<div class="p-2 border-bottom border-secondary small text-info">${i.nome} - ${i.status}</div>`; });
            data.historico.forEach(i => {
                hHist += `<div class="card p-3 mb-2 shadow-sm">
                    <div class="small fw-bold text-white mb-1">${i.nome}</div>
                    <div class="link-result mb-2">${i.link}</div>
                    <button class="btn btn-sm btn-info w-100" onclick="navigator.clipboard.writeText('${i.link}');alert('Copiado!')">COPIAR LINK</button>
                </div>`;
            });
            document.getElementById('fila').innerHTML = hFila || '<span class="text-muted small">Vazio</span>';
            document.getElementById('historico').innerHTML = hHist;
        });
    }
    setInterval(update, 4000); update();
</script>
</body>
</html>
EOC

# 8. Firewall e Inicialização
sudo ufw allow 3000/tcp > /dev/null 2>&1
chmod +x install.sh
pkill -f app.py
nohup python3 app.py > /dev/null 2>&1 &

echo "✅ INSTALAÇÃO E EXECUÇÃO CONCLUÍDAS!"
echo "Acesse: http://$(curl -s ifconfig.me):3000"
EOF
chmod +x install.sh && ./install.sh
