#!/usr/bin/env python3
# VLB Free - ilhas caseiras no LINUX (out/2026). Mesmo sistema do instalador do Windows (vagas 01 a 16),
# so que cada ilha e um servico do systemd (vlbfree-ilha@NN) que liga sozinho junto com o computador.
#
#   vlbfree-ilha                 painel "Minhas ilhas" no terminal
#   vlbfree-ilha criar [NN]      cria uma ilha (pede avatar, senha e nome da ilha)
#   vlbfree-ilha iniciar NN      liga a ilha (e passa a ligar sozinha no boot)
#   vlbfree-ilha parar NN        desliga a ilha (e para de ligar no boot)
#   vlbfree-ilha console NN      abre o console do OpenSim (sair sem desligar: Ctrl+A e depois D)
#   vlbfree-ilha status          lista as ilhas
#   vlbfree-ilha remover NN      tira a ilha do mapa e libera a vaga
#   vlbfree-ilha regenerar NN    refaz a configuracao a partir dos modelos
#   vlbfree-ilha desinstalar     remove tudo deste computador
# Uso interno: preparar NN (systemd, antes de ligar), _parar NN PID (systemd), atualizar (timer de 5 min).
#
# So usa a biblioteca padrao do Python 3. Pastas: programa em /opt/vlbfree-ilha, dados em /var/lib/vlbfree-ilha.
import getpass
import json
import locale
import os
import pwd
import re
import shutil
import socket
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request

VERSAO = '0.1.4-beta'
USO = '''vlbfree-ilha                 Minhas ilhas (painel) / My islands (panel)
vlbfree-ilha criar [NN]      criar ilha / create island
vlbfree-ilha iniciar NN      ligar / start
vlbfree-ilha parar NN        desligar / stop
vlbfree-ilha console NN      console do OpenSim (Ctrl+A D sai / leaves)
vlbfree-ilha status          lista / list
vlbfree-ilha remover NN      remover / remove
vlbfree-ilha regenerar NN    refazer configuracao / regenerate config
vlbfree-ilha tunel NN        ligar o tunel do VLB Free / turn on the VLB Free tunnel
vlbfree-ilha desinstalar     remover tudo / uninstall'''
PROG = '/opt/vlbfree-ilha'
DADOS = '/var/lib/vlbfree-ilha'
USUARIO = 'vlbfree'
API = 'https://www.vlbfree.com/api/ilha.php'
MAX_ILHAS = 16
SAIDA_RECUSADA = 78   # systemd: RestartPreventExitStatus (ilha nao aprovada = nao adianta tentar de novo)


# ---------------------------------------------------------------- idioma
def _idioma():
    try:
        with open(os.path.join(DADOS, 'idioma.txt'), encoding='utf-8') as f:
            v = f.read().strip()
            if v in ('pt', 'en'):
                return v
    except OSError:
        pass
    for var in ('LC_ALL', 'LC_MESSAGES', 'LANG', 'LANGUAGE'):
        if os.environ.get(var):
            return 'pt' if os.environ[var].lower().startswith('pt') else 'en'
    try:
        return 'pt' if (locale.getlocale()[0] or '').lower().startswith('pt') else 'en'
    except Exception:
        return 'en'


LANG = _idioma()
TEXTOS = {
    'pt': {
        'titulo': 'VLB Free - Minhas ilhas',
        'recursos': 'Este computador tem {0} GB de memória: recomendamos até {1} ilha(s) ligada(s) ao mesmo tempo.\nCada ilha LIGADA usa cerca de 0,5 a 1 GB. Você pode ter até 16 ilhas instaladas.',
        'col': ' Vaga  Ilha                              Situação    Acesso dos visitantes',
        'livre': '(livre)', 'ligada': 'LIGADA', 'desligada': 'desligada',
        'acesso_tunel': 'túnel do VLB Free (porta {0})', 'acesso_direto': 'direto (porta {0})',
        'menu': '\n[c] Criar ilha  [i] Iniciar  [p] Parar  [v] Ver console  [r] Remover  [g] Regenerar  [a] Atualizar lista  [s] Sair\nEscolha: ',
        'qual_vaga': 'Número da vaga (01 a 16): ', 'vaga_invalida': 'Vaga inválida.',
        'nenhuma': '(nenhuma ilha neste computador ainda: use [c] para criar)',
        'campo_ilha': 'Nome da ilha (3 a 32 letras/números): ', 'campo_nome': 'Primeiro nome do seu avatar no VLB Free: ',
        'campo_sobrenome': 'Sobrenome do seu avatar: ', 'campo_senha': 'Senha do avatar (não aparece ao digitar): ',
        'modo_texto': '\nComo os visitantes vão chegar à sua ilha?\n  1) Automático, sem mexer no roteador (recomendado). Se a internet não deixar chegar direto\n     (CGNAT, roteador fechado), a ilha liga sozinha o túnel do VLB Free.\n  2) Vou redirecionar a porta no meu roteador (mais rápido; precisa saber o básico de roteador).\nEscolha [1]: ',
        'criando': 'Registrando a ilha no VLB Free...',
        'falhou': 'Não deu certo: ', 'erro_conexao': 'Erro ao falar com o VLB Free: ',
        'pronto': '\nIlha registrada (pedido #{0})!\n  Ilha: {1}\n  Endereço: {2}\n  Lugar no mapa: {3}, {4}\n\n{5}\n{6}',
        'aprovada': '1) Sua ilha já foi APROVADA!', 'aguarde': '1) Aguarde a aprovação (você recebe a resposta por e-mail).',
        'passos_auto': '2) Ligue a ilha:  vlbfree-ilha iniciar {0}\n   Ela passa a ligar sozinha sempre que o computador ligar.',
        'passos_roteador': '2) No roteador, redirecione a porta {0} (TCP e UDP) para este computador (IP local {1}).\n3) Ligue a ilha:  vlbfree-ilha iniciar {2}',
        'ligar_agora': '\nLigar a ilha agora? [S/n] ',
        'nao_configurada': 'A vaga {0} ainda não tem ilha. Use:  vlbfree-ilha criar',
        'ja_ligada': 'A ilha {0} já está ligada.',
        'muitas_ligadas': 'Já há {0} ilha(s) ligada(s) e este computador aguenta bem até {1}. Ligar mais uma pode deixar tudo lento.\nLigar assim mesmo? [s/N] ',
        'ligando': 'Ligando a ilha {0} (a primeira vez demora 1 a 3 minutos)...',
        'ligou': 'Ilha {0} ligada. Console:  vlbfree-ilha console {1}   (sair sem desligar: Ctrl+A e depois D)',
        'nao_ligou': 'A ilha {0} não ligou. Motivo (últimas linhas):',
        'parando': 'Desligando a ilha {0} com segurança (até 2 minutos)...', 'parou': 'Ilha {0} desligada.',
        'desligada_ja': 'A ilha {0} já está desligada.',
        'console_desligada': 'A ilha {0} está desligada. Ligue com:  vlbfree-ilha iniciar {1}',
        'console_dica': 'Abrindo o console da ilha {0}. Para SAIR sem desligar a ilha: Ctrl+A e depois D.\n(Enter para continuar)',
        'remover_ligada': 'A ilha {0} está LIGADA. Desligar agora para remover? [s/N] ',
        'remover_confirma': 'Remover a ilha {0} da vaga {1}?\nEla sai do mapa do VLB Free, o nome fica livre e a vaga {1} fica livre neste computador. [s/N] ',
        'apagar_dados': 'Apagar também os dados da ilha {0} (terreno e objetos)?\n  s = apaga tudo\n  n = guarda uma cópia em {1}\n[s/N] ',
        'removida': 'Ilha {0} removida. A vaga {1} está livre.',
        'regenerada_n': 'Configuração da ilha {0} regenerada (vale na próxima vez que ligar).',
        'todas_ocupadas': 'Você já tem as 16 ilhas possíveis neste computador. Remova uma para criar outra.',
        'vaga_ocupada': 'A vaga {0} já tem a ilha {1}.',
        'sem_internet': 'Não consegui falar com o VLB Free (internet?): ', 'recusou': 'O VLB Free recusou: ',
        'st_pending': "A ilha '{0}' ainda está aguardando aprovação da equipe do VLB Free.",
        'st_rejected': "O pedido da ilha '{0}' foi recusado. Escreva para contato@vlbfree.com.",
        'st_suspended': "A ilha '{0}' está suspensa. Escreva para contato@vlbfree.com.",
        'st_removed': "A ilha '{0}' foi removida. Crie uma ilha nova com:  vlbfree-ilha criar",
        'porta_testando': 'Testando se a internet alcança a ilha (porta {0})...',
        'porta_aberta': 'Porta {0} aberta: os visitantes chegam direto a este computador.',
        'porta_fechada': 'A internet não deixa os visitantes chegarem direto (CGNAT ou roteador fechado). Ligando o túnel do VLB Free.',
        'porta_fechada_roteador': 'ATENÇÃO: a porta {0} continua fechada. Confira o redirecionamento no roteador ou mude para o automático com:  vlbfree-ilha tunel {1}',
        'porta_sem_teste': 'Não deu para testar a porta agora ({0}); a ilha vai abrir assim mesmo.',
        'tunel_ok': 'Túnel do VLB Free ligado (porta {0}). Os visitantes chegam pelo servidor do VLB Free.',
        'tunel_falhou': 'Não consegui ligar o túnel: {0}. A ilha vai abrir, mas os visitantes podem não conseguir chegar.',
        'iniciando': "'{0}' aprovada. Endereço: {1} (IP {2}). Iniciando...",
        'desinstalar_confirma': 'Remover o VLB Free deste computador?\nTodas as ilhas saem do mapa do VLB Free e os serviços são apagados. [s/N] ',
        'desinstalar_dados': 'Apagar também os dados de TODAS as ilhas (terrenos e objetos) em {0}? [s/N] ',
        'desinstalado': 'VLB Free removido deste computador.', 'dados_ficaram': 'Os dados das ilhas ficaram em {0}.',
        'precisa_root': 'Este comando precisa de permissão de administrador (sudo).',
        'enter': '(Enter para voltar)',
        'sim': ('s', 'sim', 'y', 'yes'),
    },
    'en': {
        'titulo': 'VLB Free - My islands',
        'recursos': 'This computer has {0} GB of memory: we recommend up to {1} island(s) ON at the same time.\nEach island that is ON uses about 0.5 to 1 GB. You can have up to 16 islands installed.',
        'col': ' Slot  Island                            Status      Visitor access',
        'livre': '(free)', 'ligada': 'ON', 'desligada': 'off',
        'acesso_tunel': 'VLB Free tunnel (port {0})', 'acesso_direto': 'direct (port {0})',
        'menu': '\n[c] Create island  [i] Start  [p] Stop  [v] View console  [r] Remove  [g] Regenerate  [a] Refresh  [s] Quit\nChoice: ',
        'qual_vaga': 'Slot number (01 to 16): ', 'vaga_invalida': 'Invalid slot.',
        'nenhuma': '(no islands on this computer yet: use [c] to create one)',
        'campo_ilha': 'Island name (3 to 32 letters/numbers): ', 'campo_nome': 'First name of your VLB Free avatar: ',
        'campo_sobrenome': 'Last name of your avatar: ', 'campo_senha': 'Avatar password (hidden while typing): ',
        'modo_texto': '\nHow will visitors reach your island?\n  1) Automatic, no router changes (recommended). If your connection does not let them reach you\n     directly (CGNAT, closed router), the island turns on the VLB Free tunnel by itself.\n  2) I will forward the port on my router (faster; needs basic router knowledge).\nChoice [1]: ',
        'criando': 'Registering the island with VLB Free...',
        'falhou': 'It did not work: ', 'erro_conexao': 'Error talking to VLB Free: ',
        'pronto': '\nIsland registered (request #{0})!\n  Island: {1}\n  Address: {2}\n  Map position: {3}, {4}\n\n{5}\n{6}',
        'aprovada': '1) Your island is already APPROVED!', 'aguarde': '1) Wait for approval (you will get an e-mail).',
        'passos_auto': '2) Start the island:  vlbfree-ilha iniciar {0}\n   From then on it starts by itself whenever the computer boots.',
        'passos_roteador': '2) On your router, forward port {0} (TCP and UDP) to this computer (local IP {1}).\n3) Start the island:  vlbfree-ilha iniciar {2}',
        'ligar_agora': '\nStart the island now? [Y/n] ',
        'nao_configurada': 'Slot {0} has no island yet. Use:  vlbfree-ilha criar',
        'ja_ligada': 'Island {0} is already on.',
        'muitas_ligadas': 'There are already {0} island(s) on and this computer handles up to {1} well. One more may slow everything down.\nStart anyway? [y/N] ',
        'ligando': 'Starting island {0} (the first time takes 1 to 3 minutes)...',
        'ligou': 'Island {0} is on. Console:  vlbfree-ilha console {1}   (leave without stopping it: Ctrl+A then D)',
        'nao_ligou': 'Island {0} did not start. Reason (last lines):',
        'parando': 'Shutting island {0} down safely (up to 2 minutes)...', 'parou': 'Island {0} is off.',
        'desligada_ja': 'Island {0} is already off.',
        'console_desligada': 'Island {0} is off. Start it with:  vlbfree-ilha iniciar {1}',
        'console_dica': 'Opening the console of island {0}. To LEAVE without stopping the island: Ctrl+A then D.\n(Enter to continue)',
        'remover_ligada': 'Island {0} is ON. Stop it now to remove it? [y/N] ',
        'remover_confirma': 'Remove island {0} from slot {1}?\nIt leaves the VLB Free map, its name becomes free and slot {1} becomes free on this computer. [y/N] ',
        'apagar_dados': 'Also delete the data of island {0} (terrain and objects)?\n  y = delete everything\n  n = keep a copy in {1}\n[y/N] ',
        'removida': 'Island {0} removed. Slot {1} is free.',
        'regenerada_n': 'Configuration of island {0} regenerated (applies the next time it starts).',
        'todas_ocupadas': 'You already have the 16 possible islands on this computer. Remove one to create another.',
        'vaga_ocupada': 'Slot {0} already has the island {1}.',
        'sem_internet': 'Could not reach VLB Free (internet?): ', 'recusou': 'VLB Free refused: ',
        'st_pending': "The island '{0}' is still waiting for approval from the VLB Free team.",
        'st_rejected': "The request for island '{0}' was declined. Write to contato@vlbfree.com.",
        'st_suspended': "The island '{0}' is suspended. Write to contato@vlbfree.com.",
        'st_removed': "The island '{0}' was removed. Create a new one with:  vlbfree-ilha criar",
        'porta_testando': 'Testing whether the internet can reach the island (port {0})...',
        'porta_aberta': 'Port {0} is open: visitors reach this computer directly.',
        'porta_fechada': 'Your connection does not let visitors reach you directly (CGNAT or closed router). Turning on the VLB Free tunnel.',
        'porta_fechada_roteador': 'WARNING: port {0} is still closed. Check the forwarding on your router or switch to automatic mode with:  vlbfree-ilha tunel {1}',
        'porta_sem_teste': 'Could not test the port now ({0}); the island will start anyway.',
        'tunel_ok': 'VLB Free tunnel is on (port {0}). Visitors arrive through the VLB Free server.',
        'tunel_falhou': 'Could not turn on the tunnel: {0}. The island will start, but visitors may not be able to arrive.',
        'iniciando': "'{0}' approved. Address: {1} (IP {2}). Starting...",
        'desinstalar_confirma': 'Remove VLB Free from this computer?\nAll islands leave the VLB Free map and the services are deleted. [y/N] ',
        'desinstalar_dados': 'Also delete the data of ALL islands (terrain and objects) in {0}? [y/N] ',
        'desinstalado': 'VLB Free removed from this computer.', 'dados_ficaram': 'The island data was kept in {0}.',
        'precisa_root': 'This command needs administrator permission (sudo).',
        'enter': '(Enter to go back)',
        'sim': ('y', 'yes', 's', 'sim'),
    },
}


def T(chave):
    return TEXTOS[LANG].get(chave, TEXTOS['pt'][chave])


def sim(resposta, padrao=False):
    r = (resposta or '').strip().lower()
    return padrao if not r else r in T('sim')


# ---------------------------------------------------------------- utilidades
def num(n):
    return '%02d' % int(n)


def pasta_ilha(n):
    return os.path.join(DADOS, 'ilhas', num(n))


def json_ilha(n):
    return os.path.join(pasta_ilha(n), 'ilha.json')


def ler_ilha(n):
    try:
        with open(json_ilha(n), encoding='utf-8') as f:
            return json.load(f)
    except (OSError, ValueError):
        return None


def dono_vlbfree(caminho):
    """arquivos criados pelo root nas pastas das ilhas passam a ser do usuario da ilha"""
    if os.geteuid() != 0:
        return
    try:
        u = pwd.getpwnam(USUARIO)
        os.chown(caminho, u.pw_uid, u.pw_gid)
    except (KeyError, OSError):
        pass


def gravar_texto(caminho, texto, modo=None):
    tmp = caminho + '.tmp'
    with open(tmp, 'w', encoding='utf-8', newline='\n') as f:
        f.write(texto)
    if modo is not None:
        os.chmod(tmp, modo)
    os.replace(tmp, caminho)
    dono_vlbfree(caminho)


def gravar_ilha(n, dados):
    os.makedirs(pasta_ilha(n), exist_ok=True)
    dono_vlbfree(pasta_ilha(n))
    # o ilha.json guarda o token da ilha: so o dono da ilha (usuario vlbfree) e o root leem
    gravar_texto(json_ilha(n), json.dumps(dados, ensure_ascii=False, indent=2) + '\n', 0o600)


def ilhas_instaladas():
    return [n for n in range(1, MAX_ILHAS + 1) if os.path.exists(json_ilha(n))]


def servico(n):
    return 'vlbfree-ilha@%s.service' % num(n)


def nome_tunel(n):
    return 'vlbfree-ilha-' + num(n)          # 15 letras: o maximo de um nome de interface no Linux


def ilha_rodando(n):
    return subprocess.run(['systemctl', 'is-active', '--quiet', servico(n)]).returncode == 0


def ilhas_ligadas():
    return [n for n in ilhas_instaladas() if ilha_rodando(n)]


def ram_gb():
    try:
        with open('/proc/meminfo') as f:
            for linha in f:
                if linha.startswith('MemTotal:'):
                    return round(int(linha.split()[1]) / 1024 / 1024, 1)
    except OSError:
        pass
    return 4.0


def ilhas_recomendadas():
    return int(min(MAX_ILHAS, max(1, (ram_gb() - 4) // 1.5)))


def api(dados, tempo=30):
    dados = dict(dados)
    dados.setdefault('lang', LANG)
    corpo = urllib.parse.urlencode(dados).encode()
    req = urllib.request.Request(API, data=corpo, headers={'User-Agent': 'VLBFree-Ilha-Linux/' + VERSAO})
    try:
        with urllib.request.urlopen(req, timeout=tempo) as r:
            return json.loads(r.read().decode('utf-8'))
    except urllib.error.HTTPError as e:
        # a API responde erros com JSON (ex.: senha errada) e codigo 4xx
        try:
            return json.loads(e.read().decode('utf-8'))
        except Exception:
            raise e


def porta_em_uso(porta):
    for tipo in (socket.SOCK_STREAM, socket.SOCK_DGRAM):
        s = socket.socket(socket.AF_INET, tipo)
        try:
            s.bind(('0.0.0.0', porta))
        except OSError:
            return True
        finally:
            s.close()
    return False


def porta_livre():
    """primeira porta livre a partir da 9000: nem em uso agora, nem reservada por outra ilha deste computador"""
    reservadas = {int((ler_ilha(n) or {}).get('porta', 0)) for n in ilhas_instaladas()}
    for p in range(9000, 9100):
        if p not in reservadas and not porta_em_uso(p):
            return p
    return 9000


def ip_local():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.connect(('65.21.163.13', 80))       # nao envia nada: so descobre a placa que sai para a internet
        return s.getsockname()[0]
    except OSError:
        return '?'
    finally:
        s.close()


def trocar_linha(caminho, padrao, nova):
    with open(caminho, encoding='utf-8') as f:
        txt = f.read()
    txt2, qtd = re.subn(padrao, nova, txt, flags=re.M)
    if qtd == 0:
        return False
    if txt2 != txt:
        gravar_texto(caminho, txt2)
    return True


def gerar_config(n, i):
    """gera a configuracao do OpenSim da ilha N a partir dos modelos (igual ao Windows)"""
    d = pasta_ilha(n)
    for sub in ('config-include', 'Regions', 'dados', 'cache'):
        os.makedirs(os.path.join(d, sub), exist_ok=True)
        dono_vlbfree(os.path.join(d, sub))
    troca = {
        '{ILHA_DIR}': d, '{PORTA}': str(i['porta']), '{ILHA_NOME}': i['ilha'], '{ILHA_UUID}': i['uuid'],
        '{ILHA_X}': str(i['x']), '{ILHA_Y}': str(i['y']), '{IP_PUBLICO}': i.get('host') or i.get('ip') or '',
        '{DONO_NOME}': i['dono'],
    }
    modelos = os.path.join(PROG, 'ilha-templates')
    for origem, destino in (('OpenSim.ini', 'OpenSim.ini'), ('Regions.ini', 'Regions/Regions.ini'),
                            ('config-include/GridCommon.ini', 'config-include/GridCommon.ini'),
                            ('config-include/GridHypergrid.ini', 'config-include/GridHypergrid.ini'),
                            ('config-include/FlotsamCache.ini', 'config-include/FlotsamCache.ini'),
                            ('config-include/osslDefaultEnable.ini', 'config-include/osslDefaultEnable.ini'),
                            ('config-include/osslEnable.ini', 'config-include/osslEnable.ini')):
        with open(os.path.join(modelos, origem), encoding='utf-8-sig') as f:
            txt = f.read()
        for k, v in troca.items():
            txt = txt.replace(k, v)
        gravar_texto(os.path.join(d, destino), txt.replace('\r\n', '\n'))
    # ilha em tunel: porta do tunel e UDP preso ao IP do tunel (ver ligar_tunel)
    if i.get('tunel') and i.get('tunel_ip'):
        trocar_linha(os.path.join(d, 'Regions', 'Regions.ini'), r'^InternalAddress\s*=.*$', 'InternalAddress = ' + i['tunel_ip'])


def log_ilha(n, texto):
    try:
        caminho = os.path.join(pasta_ilha(n), 'vlbfree.log')
        linhas = []
        if os.path.exists(caminho):
            with open(caminho, encoding='utf-8', errors='replace') as f:
                linhas = f.read().splitlines()[-199:]
        linhas.append(time.strftime('%Y-%m-%d %H:%M:%S') + '  ' + texto)
        gravar_texto(caminho, '\n'.join(linhas) + '\n')
    except OSError:
        pass


def avisar(n, texto):
    """mensagem que aparece no journal do servico (systemctl status) e no vlbfree.log da ilha"""
    print(texto, flush=True)
    log_ilha(n, texto)


def firewall_liberar_interface(iface):
    if shutil.which('ufw') and 'Status: active' in subprocess.run(['ufw', 'status'], capture_output=True, text=True).stdout:
        subprocess.run(['ufw', 'allow', 'in', 'on', iface, 'comment', 'VLB Free tunel'], capture_output=True)
    if shutil.which('firewall-cmd') and subprocess.run(['firewall-cmd', '--state'], capture_output=True).returncode == 0:
        for extra in ([], ['--permanent']):
            subprocess.run(['firewall-cmd', '--zone=trusted', '--add-interface=' + iface] + extra, capture_output=True)


def firewall_tirar_interface(iface):
    if shutil.which('ufw'):
        subprocess.run(['ufw', 'delete', 'allow', 'in', 'on', iface], capture_output=True)
    if shutil.which('firewall-cmd') and subprocess.run(['firewall-cmd', '--state'], capture_output=True).returncode == 0:
        for extra in ([], ['--permanent']):
            subprocess.run(['firewall-cmd', '--zone=trusted', '--remove-interface=' + iface] + extra, capture_output=True)


# ---------------------------------------------------------------- tunel (CGNAT / roteador fechado)
def ligar_tunel(n):
    """A ilha conecta de dentro para fora no servidor do VLB Free (WireGuard) e os visitantes chegam por la.
    Cada ilha tem o proprio tunel (chave, IP 10.77.x, porta 30000+). Como TODAS as ilhas falam com o mesmo
    10.77.0.1, cada tunel usa uma tabela de rotas propria escolhida pelo IP de origem (Table = off + ip rule)
    e o UDP da ilha fica preso ao IP do tunel (InternalAddress) - assim varias ilhas em tunel convivem."""
    i = ler_ilha(n)
    wg = shutil.which('wg')
    if not wg:
        raise RuntimeError('wireguard-tools nao instalado')
    # a chave fica junto da configuracao do WireGuard (/etc/wireguard: so o root le), nao na pasta da ilha
    iface = nome_tunel(n)
    os.makedirs('/etc/wireguard', mode=0o700, exist_ok=True)
    chave_arq = '/etc/wireguard/%s.key' % iface
    if not os.path.exists(chave_arq):
        priv = subprocess.run([wg, 'genkey'], capture_output=True, text=True, check=True).stdout.strip()
        with open(os.open(chave_arq, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), 'w') as f:
            f.write(priv + '\n')
    with open(chave_arq) as f:
        priv = f.read().strip()
    pub = subprocess.run([wg, 'pubkey'], input=priv + '\n', capture_output=True, text=True, check=True).stdout.strip()
    if not re.fullmatch(r'[A-Za-z0-9+/]{42,43}=', pub):
        raise RuntimeError('chave publica invalida')

    r = api({'acao': 'tunel', 'id': i['id'], 'token': i['token'], 'chave': pub}, 60)
    if not r.get('ok'):
        raise RuntimeError('o VLB Free recusou: %s' % r.get('erro'))
    tip, porta = r['tunel_ip'], int(r['porta'])
    log_ilha(n, 'servidor: tunel %s porta %s via %s' % (tip, porta, r['servidor']))

    tabela = 51770 + int(n)
    conf = ('[Interface]\nPrivateKey = %s\nAddress = %s/32\nTable = off\n'
            'PostUp = ip rule add from %s lookup %d; ip route replace 10.77.0.1/32 dev %%i table %d\n'
            'PostDown = ip rule del from %s lookup %d\n\n'
            '[Peer]\nPublicKey = %s\nEndpoint = %s\nAllowedIPs = 10.77.0.1/32\nPersistentKeepalive = 25\n'
            % (priv, tip, tip, tabela, tabela, tip, tabela, r['servidor_chave'], r['servidor']))
    caminho = '/etc/wireguard/%s.conf' % iface
    with open(os.open(caminho + '.tmp', os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), 'w') as f:
        f.write(conf)
    os.replace(caminho + '.tmp', caminho)
    subprocess.run(['systemctl', 'enable', 'wg-quick@' + iface], capture_output=True)
    p = subprocess.run(['systemctl', 'restart', 'wg-quick@' + iface], capture_output=True, text=True)
    if p.returncode != 0:
        raise RuntimeError('o servico do tunel nao ligou (journalctl -u wg-quick@%s)' % iface)
    firewall_liberar_interface(iface)

    # a ilha passa a usar a porta do tunel (a porta publica e a mesma la no servidor)
    d = pasta_ilha(n)
    trocar_linha(os.path.join(d, 'OpenSim.ini'), r'^(\s*http_listener_port\s*=).*$', r'\g<1> %d' % porta)
    trocar_linha(os.path.join(d, 'Regions', 'Regions.ini'), r'^InternalPort\s*=.*$', 'InternalPort = %d' % porta)
    trocar_linha(os.path.join(d, 'Regions', 'Regions.ini'), r'^InternalAddress\s*=.*$', 'InternalAddress = ' + tip)
    i.update({'porta': porta, 'tunel': True, 'tunel_ip': tip})
    gravar_ilha(n, i)
    ok = subprocess.run(['ping', '-c', '2', '-W', '2', '-I', tip, '10.77.0.1'], capture_output=True).returncode == 0
    log_ilha(n, 'tunel ligado; porta da ilha = %d; ping no servidor pelo tunel: %s' % (porta, ok))
    return porta


def tirar_tunel(n):
    iface = nome_tunel(n)
    subprocess.run(['systemctl', 'disable', '--now', 'wg-quick@' + iface], capture_output=True)
    for caminho in ('/etc/wireguard/%s.conf' % iface, '/etc/wireguard/%s.key' % iface):
        try:
            os.remove(caminho)
        except OSError:
            pass
    firewall_tirar_interface(iface)


def testar_porta(i, porta):
    """abre a porta da ilha por alguns segundos e pede ao servidor que bata nela (TCP e UDP, com um codigo)"""
    try:
        tl = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        tl.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        tl.bind(('0.0.0.0', porta))
        tl.listen(4)
        ul = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        ul.bind(('0.0.0.0', porta))
    except OSError:
        return 'ocupada'
    try:
        t = api({'acao': 'testar_porta', 'id': i['id'], 'token': i['token'], 'porta': str(porta)}, 40)
        if not t.get('ok'):
            return 'erro'
        esperado = 'VLBFREE %s' % t['codigo']
        time.sleep(0.5)
        tcp_ok = udp_ok = False
        tl.settimeout(0.5)
        try:
            c, _ = tl.accept()
            c.settimeout(3)
            try:
                tcp_ok = c.makefile('r', encoding='ascii', errors='replace').readline().strip() == esperado
                c.recv(64)      # deixa o servidor fechar primeiro (o TIME_WAIT fica la, e a porta fica livre para a ilha)
            except OSError:
                pass
            c.close()
        except OSError:
            pass
        ul.settimeout(0.5)
        while True:
            try:
                dado, _ = ul.recvfrom(512)
            except OSError:
                break
            if dado.decode('ascii', 'replace').strip() == esperado:
                udp_ok = True
        return 'aberta' if (tcp_ok and udp_ok) else 'fechada'
    except Exception:
        return 'erro'
    finally:
        tl.close()
        ul.close()


# ---------------------------------------------------------------- comandos do systemd
def liberacao(n, valor=None):
    """o 'preparar' (root) deixa escrito se a ilha pode ligar; o 'rodar' (usuario da ilha) obedece.
    Assim a recusa sai do processo principal e o RestartPreventExitStatus=78 vale (no ExecStartPre ele nao vale)."""
    caminho = os.path.join(pasta_ilha(n), '.liberacao')
    if valor is not None:
        gravar_texto(caminho, valor + '\n')
        return valor
    try:
        with open(caminho, encoding='utf-8') as f:
            return f.read().strip()
    except OSError:
        return ''


def cmd_preparar(n):
    """ExecStartPre (root): confere a ilha no VLB Free, testa a porta / liga o tunel e ajusta o endereco."""
    i = ler_ilha(n)
    if not i:
        print(T('nao_configurada').format(num(n)))
        return 0                                  # o 'rodar' nao acha a liberacao e sai com 78
    liberacao(n, 'conferindo')
    try:
        r = api({'acao': 'ping', 'id': i['id'], 'token': i['token'], 'inicio': '1', 'versao': 'lx-' + VERSAO})
    except Exception as e:
        avisar(n, T('sem_internet') + str(e))
        return 1                                  # sem internet ainda (boot): o systemd tenta de novo em 1 minuto
    if not r.get('ok'):
        avisar(n, T('recusou') + str(r.get('erro')))
        liberacao(n, 'recusada')
        return 0
    if r.get('aviso_versao'):                     # versao nova do programa: o servidor avisa antes de exigir
        avisar(n, r['aviso_versao'])
    status = r['ilha'].get('status')
    if status in ('pending', 'rejected', 'suspended', 'removed'):
        avisar(n, T('st_' + status).format(i['ilha']))
        liberacao(n, 'recusada')
        return 0

    if i.get('tunel'):
        iface = nome_tunel(n)
        ativo = subprocess.run(['systemctl', 'is-active', '--quiet', 'wg-quick@' + iface]).returncode == 0
        if not ativo or not os.path.exists('/etc/wireguard/%s.conf' % iface):
            try:
                avisar(n, T('tunel_ok').format(ligar_tunel(n)))
            except Exception as e:
                avisar(n, T('tunel_falhou').format(e))
    else:
        avisar(n, T('porta_testando').format(i['porta']))
        teste = testar_porta(i, int(i['porta']))
        if teste == 'fechada':                    # confirma antes de concluir "fechada"
            time.sleep(2)
            teste = testar_porta(i, int(i['porta']))
        if teste == 'aberta':
            avisar(n, T('porta_aberta').format(i['porta']))
        elif teste == 'fechada' and i.get('modo') == 'roteador':
            avisar(n, T('porta_fechada_roteador').format(i['porta'], num(n)))
        elif teste == 'fechada':
            avisar(n, T('porta_fechada'))
            try:
                avisar(n, T('tunel_ok').format(ligar_tunel(n)))
            except Exception as e:
                avisar(n, T('tunel_falhou').format(e))
        else:
            avisar(n, T('porta_sem_teste').format(teste))

    # endereco publico: <ilha>.ilhas.vlbfree.com (o servidor atualiza o DNS quando o IP muda); sem nome, o IP
    endereco = r['ilha'].get('host') or r['ilha'].get('ip')
    trocar_linha(os.path.join(pasta_ilha(n), 'Regions', 'Regions.ini'), r'^ExternalHostName\s*=.*$', 'ExternalHostName = ' + endereco)
    avisar(n, T('iniciando').format(i['ilha'], endereco, r['ilha'].get('ip')))
    liberacao(n, 'ok')
    return 0


def cmd_rodar(n):
    """ExecStart (usuario da ilha): liga o OpenSim dentro de um 'screen' (o console da ilha), se o preparar liberou."""
    if liberacao(n) != 'ok':
        print('ilha %s nao liberada pelo VLB Free (ver acima)' % num(n), flush=True)
        return SAIDA_RECUSADA
    tela = shutil.which('screen') or '/usr/bin/screen'
    os.chdir(os.path.join(PROG, 'app'))
    os.execv(tela, [tela, '-DmS', 'vlbfree-ilha-' + num(n), os.path.join(PROG, 'runtime', 'dotnet'), 'OpenSim.dll',
                    '-inifile=' + os.path.join(pasta_ilha(n), 'OpenSim.ini'), '-console=basic'])


def cmd_parar_systemd(n, pid):
    """ExecStop (root): manda 'quit' ao console do OpenSim e espera ele terminar (o systemd mata o que sobrar)."""
    sessao = 'vlbfree-ilha-' + num(n)
    subprocess.run(['runuser', '-u', USUARIO, '--', 'screen', '-S', sessao, '-p', '0', '-X', 'stuff', 'quit\r'], capture_output=True)
    fim = time.time() + 120
    while time.time() < fim and pid and os.path.exists('/proc/%s' % pid):
        time.sleep(1)
    return 0


def cmd_atualizar():
    """timer de 5 minutos: avisa o IP atual de cada ilha (DDNS) e manda os numeros de uso dela."""
    for n in ilhas_instaladas():
        i = ler_ilha(n)
        if not i:
            continue
        corpo = {'acao': 'ping', 'id': i['id'], 'token': i['token']}
        try:
            with urllib.request.urlopen('http://127.0.0.1:%s/jsonSimStats/' % i['porta'], timeout=10) as r:
                s = json.loads(r.read().decode('utf-8'))
            corpo.update({'prims': str(int(float(s.get('Prims', 0)))), 'scripts': str(int(float(s.get('AtvScr', 0)))),
                          'agents': str(int(float(s.get('RootAg', 0)))), 'fps': '%.1f' % float(s.get('SimFPS', 0)),
                          'uptime': re.sub(r'\.\d+$', '', str(s.get('Uptime', '')))})
        except Exception:
            pass
        try:
            bancos = [os.path.join(pasta_ilha(n), 'dados', a) for a in os.listdir(os.path.join(pasta_ilha(n), 'dados')) if a.startswith('ilha.db')]
            if bancos:
                corpo['db_mb'] = '%.1f' % (max(os.path.getsize(b) for b in bancos) / 1048576)
                corpo.setdefault('prims', '0')
        except OSError:
            pass
        try:
            r = api(corpo)
            msg = ('ok  status=%s  ip=%s  nome=%s  prims=%s  fps=%s' % (r['ilha'].get('status'), r['ilha'].get('ip'), r['ilha'].get('host'),
                                                                     corpo.get('prims'), corpo.get('fps'))) if r.get('ok') else 'recusado: %s' % r.get('erro')
        except Exception as e:
            msg = 'sem conexao: %s' % e
        caminho = os.path.join(pasta_ilha(n), 'atualizador.log')
        try:
            linhas = []
            if os.path.exists(caminho):
                with open(caminho, encoding='utf-8', errors='replace') as f:
                    linhas = f.read().splitlines()[-199:]
            linhas.append(time.strftime('%Y-%m-%d %H:%M') + '  ' + msg)
            gravar_texto(caminho, '\n'.join(linhas) + '\n')
        except OSError:
            pass
    return 0


# ---------------------------------------------------------------- comandos do usuario
def pedir(texto):
    try:
        return input(texto)
    except EOFError:
        return ''


def cmd_criar(n=None):
    if n is None:
        livres = [k for k in range(1, MAX_ILHAS + 1) if not os.path.exists(json_ilha(k))]
        if not livres:
            print(T('todas_ocupadas'))
            return 1
        n = livres[0]
    if ler_ilha(n):
        print(T('vaga_ocupada').format(num(n), ler_ilha(n)['ilha']))
        return 1
    print('\n== ' + T('titulo') + ' - ' + num(n) + ' ==')
    ilha = pedir(T('campo_ilha')).strip()
    nome = pedir(T('campo_nome')).strip()
    sobrenome = pedir(T('campo_sobrenome')).strip()
    senha = getpass.getpass(T('campo_senha'))
    modo = 'roteador' if pedir(T('modo_texto')).strip() == '2' else 'auto'
    print(T('criando'))
    try:
        r = api({'acao': 'pedir', 'first': nome, 'last': sobrenome, 'password': senha, 'ilha': ilha, 'porta': str(porta_livre())}, 60)
    except Exception as e:
        print(T('erro_conexao') + str(e))
        return 1
    if not r.get('ok'):
        print(T('falhou') + str(r.get('erro')))
        return 1
    i = r['ilha']
    dados = {'numero': num(n), 'id': i['id'], 'token': r['token'], 'ilha': i['ilha'], 'uuid': i['uuid'], 'x': i['x'], 'y': i['y'],
             'porta': i['porta'], 'ip': i.get('ip'), 'host': i.get('host'), 'dono': nome + ' ' + sobrenome, 'grid': i.get('grid'),
             'modo': modo, 'sistema': 'linux'}
    gravar_ilha(n, dados)
    gerar_config(n, dados)
    primeiro = T('aprovada') if i.get('status') == 'approved' else T('aguarde')
    passos = T('passos_roteador').format(i['porta'], ip_local(), num(n)) if modo == 'roteador' else T('passos_auto').format(num(n))
    print(T('pronto').format(i['id'], i['ilha'], i.get('host'), i['x'], i['y'], primeiro, passos))
    if i.get('status') == 'approved' and sim(pedir(T('ligar_agora')), True):
        return cmd_iniciar(n)
    return 0


def mostrar_falha(n):
    print(T('nao_ligou').format(ler_ilha(n)['ilha']))
    subprocess.run(['journalctl', '-u', servico(n), '-n', '15', '--no-pager', '-o', 'cat'])


def cmd_iniciar(n):
    i = ler_ilha(n)
    if not i:
        print(T('nao_configurada').format(num(n)))
        return 1
    if ilha_rodando(n):
        print(T('ja_ligada').format(i['ilha']))
        return 0
    ligadas, rec = len(ilhas_ligadas()), ilhas_recomendadas()
    if ligadas >= rec and not sim(pedir(T('muitas_ligadas').format(ligadas, rec))):
        return 0
    print(T('ligando').format(i['ilha']))
    subprocess.run(['systemctl', 'reset-failed', servico(n)], capture_output=True)
    subprocess.run(['systemctl', 'enable', servico(n)], capture_output=True)
    p = subprocess.run(['systemctl', 'start', servico(n)])
    if p.returncode != 0 or not ilha_rodando(n):
        mostrar_falha(n)
        return 1
    # espera o OpenSim responder na porta da ilha (ate 3 minutos)
    i = ler_ilha(n)
    fim = time.time() + 180
    while time.time() < fim and ilha_rodando(n):
        try:
            with urllib.request.urlopen('http://127.0.0.1:%s/jsonSimStats/' % i['porta'], timeout=5):
                break
        except Exception:
            time.sleep(3)
    if not ilha_rodando(n):
        mostrar_falha(n)
        return 1
    print(T('ligou').format(i['ilha'], num(n)))
    return 0


def cmd_parar(n):
    i = ler_ilha(n)
    if not i:
        print(T('nao_configurada').format(num(n)))
        return 1
    subprocess.run(['systemctl', 'disable', servico(n)], capture_output=True)
    if not ilha_rodando(n):
        print(T('desligada_ja').format(i['ilha']))
        return 0
    print(T('parando').format(i['ilha']))
    subprocess.run(['systemctl', 'stop', servico(n)])
    print(T('parou').format(i['ilha']))
    return 0


def cmd_console(n):
    i = ler_ilha(n)
    if not i:
        print(T('nao_configurada').format(num(n)))
        return 1
    if not ilha_rodando(n):
        print(T('console_desligada').format(i['ilha'], num(n)))
        return 1
    pedir(T('console_dica').format(i['ilha']))
    # o screen e do usuario vlbfree; o 'script' cria um terminal novo (senao o screen recusa o terminal do sudo)
    return subprocess.run(['runuser', '-u', USUARIO, '--', 'script', '-q', '-c',
                           'screen -r vlbfree-ilha-%s' % num(n), '/dev/null']).returncode


def cmd_remover(n):
    i = ler_ilha(n)
    if not i:
        print(T('nao_configurada').format(num(n)))
        return 1
    if ilha_rodando(n):
        if not sim(pedir(T('remover_ligada').format(i['ilha']))):
            return 0
        cmd_parar(n)
    if not sim(pedir(T('remover_confirma').format(i['ilha'], num(n)))):
        return 0
    try:
        api({'acao': 'remover', 'id': i['id'], 'token': i['token']})
    except Exception:
        pass
    subprocess.run(['systemctl', 'disable', servico(n)], capture_output=True)
    tirar_tunel(n)
    nome_seguro = re.sub(r'[\\/:*?"<>|]', '', i['ilha'])
    guarda = os.path.join(DADOS, 'ilhas-removidas', '%s - %s - %s' % (num(n), nome_seguro, time.strftime('%Y-%m-%d %H%M')))
    if sim(pedir(T('apagar_dados').format(i['ilha'], guarda))):
        shutil.rmtree(pasta_ilha(n), ignore_errors=True)
    else:
        os.makedirs(os.path.dirname(guarda), exist_ok=True)
        shutil.move(pasta_ilha(n), guarda)
    print(T('removida').format(i['ilha'], num(n)))
    return 0


def cmd_regenerar(n):
    i = ler_ilha(n)
    if not i:
        print(T('nao_configurada').format(num(n)))
        return 1
    gerar_config(n, i)
    print(T('regenerada_n').format(i['ilha']))
    return 0


def cmd_tunel(n):
    """muda a ilha para o modo automatico e liga o tunel ja (para quem escolheu roteador e nao conseguiu)"""
    i = ler_ilha(n)
    if not i:
        print(T('nao_configurada').format(num(n)))
        return 1
    i['modo'] = 'auto'
    gravar_ilha(n, i)
    try:
        print(T('tunel_ok').format(ligar_tunel(n)))
    except Exception as e:
        print(T('tunel_falhou').format(e))
        return 1
    if ilha_rodando(n):
        subprocess.run(['systemctl', 'restart', servico(n)])
    return 0


def linhas_status():
    linhas = []
    for n in ilhas_instaladas():
        i = ler_ilha(n) or {}
        rod = ilha_rodando(n)
        acesso = (T('acesso_tunel') if i.get('tunel') else T('acesso_direto')).format(i.get('porta'))
        linhas.append(' %-4s  %-32s  %-10s  %s' % (num(n), str(i.get('ilha', '?'))[:32], T('ligada') if rod else T('desligada'), acesso))
    return linhas


def cmd_status():
    print(T('col'))
    print('\n'.join(linhas_status()) or T('nenhuma'))
    return 0


def pedir_vaga():
    r = pedir(T('qual_vaga')).strip()
    if r.isdigit() and 1 <= int(r) <= MAX_ILHAS:
        return int(r)
    print(T('vaga_invalida'))
    return None


def cmd_painel():
    while True:
        print('\n' + '=' * 78)
        print(' ' + T('titulo') + '   (v' + VERSAO + ')')
        print('=' * 78)
        print(T('recursos').format(('%.1f' % ram_gb()).replace('.', ',' if LANG == 'pt' else '.'), ilhas_recomendadas()))
        print()
        cmd_status()
        op = pedir(T('menu')).strip().lower()
        if op in ('s', 'q', 'sair', 'quit'):
            return 0
        if op == '' and not sys.stdin.isatty():
            return 0
        if op in ('', 'a'):
            continue
        if op == 'c':
            cmd_criar()
        elif op in ('i', 'p', 'v', 'r', 'g'):
            n = pedir_vaga()
            if n is None:
                continue
            {'i': cmd_iniciar, 'p': cmd_parar, 'v': cmd_console, 'r': cmd_remover, 'g': cmd_regenerar}[op](n)
        pedir(T('enter'))


def cmd_desinstalar():
    if not sim(pedir(T('desinstalar_confirma'))):
        return 0
    for n in ilhas_instaladas():
        subprocess.run(['systemctl', 'disable', '--now', servico(n)], capture_output=True)
        i = ler_ilha(n)
        try:
            api({'acao': 'remover', 'id': i['id'], 'token': i['token']}, 20)
        except Exception:
            pass
        tirar_tunel(n)
    for unidade in ('vlbfree-ilha-atualizar.timer', 'vlbfree-ilha-atualizar.service'):
        subprocess.run(['systemctl', 'disable', '--now', unidade], capture_output=True)
    # instalado pelo pacote .deb: o dpkg tira os arquivos ("purge" tambem apaga os dados e o usuario)
    st = subprocess.run(['dpkg-query', '-W', '-f=${Status}', 'vlbfree-ilha'], capture_output=True, text=True) if shutil.which('dpkg-query') else None
    if st and 'install ok installed' in st.stdout:
        apagar = sim(pedir(T('desinstalar_dados').format(DADOS)))
        subprocess.run(['dpkg', '--purge' if apagar else '--remove', 'vlbfree-ilha'])
        if not apagar:
            print(T('dados_ficaram').format(DADOS))
        print(T('desinstalado'))
        return 0
    for caminho in ('/etc/systemd/system/vlbfree-ilha@.service', '/etc/systemd/system/vlbfree-ilha-atualizar.service',
                    '/etc/systemd/system/vlbfree-ilha-atualizar.timer', '/usr/local/bin/vlbfree-ilha',
                    '/usr/share/applications/vlbfree-ilhas.desktop'):
        try:
            os.remove(caminho)
        except OSError:
            pass
    subprocess.run(['systemctl', 'daemon-reload'], capture_output=True)
    if os.path.isfile('/etc/ufw/applications.d/vlbfree-ilha') and shutil.which('ufw'):
        subprocess.run(['ufw', 'delete', 'allow', 'VLB Free Ilha'], capture_output=True)
    if sim(pedir(T('desinstalar_dados').format(DADOS))):
        shutil.rmtree(DADOS, ignore_errors=True)
        subprocess.run(['userdel', USUARIO], capture_output=True)
    else:
        print(T('dados_ficaram').format(DADOS))
    shutil.rmtree(PROG, ignore_errors=True)
    print(T('desinstalado'))
    return 0


def main(args):
    cmd = args[0] if args else ''
    # o timer e o 'rodar' rodam como o usuario vlbfree; todo o resto precisa de root
    if os.geteuid() != 0 and cmd not in ('atualizar', 'rodar'):
        if shutil.which('sudo') and sys.stdin.isatty():
            os.execvp('sudo', ['sudo', sys.executable, os.path.realpath(__file__)] + args)
        print(T('precisa_root'))
        return 1
    vaga = None
    if len(args) > 1:
        if not args[1].isdigit() or not 1 <= int(args[1]) <= MAX_ILHAS:
            print(T('vaga_invalida'))
            return 2
        vaga = int(args[1])
    precisa_vaga = {'iniciar': cmd_iniciar, 'parar': cmd_parar, 'console': cmd_console, 'remover': cmd_remover,
                    'regenerar': cmd_regenerar, 'tunel': cmd_tunel, 'preparar': cmd_preparar, 'rodar': cmd_rodar}
    if cmd in precisa_vaga:
        if vaga is None:
            print(T('qual_vaga').strip())
            return 2
        return precisa_vaga[cmd](vaga)
    if cmd == '_parar':
        return cmd_parar_systemd(vaga, args[2] if len(args) > 2 else None)
    if cmd == 'criar':
        return cmd_criar(vaga)
    if cmd in ('status', 'lista'):
        return cmd_status()
    if cmd == 'atualizar':
        return cmd_atualizar()
    if cmd == 'desinstalar':
        return cmd_desinstalar()
    if cmd in ('versao', '--version', '-v'):
        print(VERSAO)
        return 0
    if cmd in ('', 'painel'):
        return cmd_painel()
    print(USO)
    return 2


if __name__ == '__main__':
    try:
        sys.exit(main(sys.argv[1:]))
    except KeyboardInterrupt:
        print()
        sys.exit(130)
