@echo off
rem turbgate Windows installer — modo simples (sem MSI).
rem
rem Uso: clique-direito -> "Executar como administrador" e responda o prompt.
rem      ou: install.bat ^<cliente_id^>
rem
rem Zelador so precisa do `cliente_id`. O cert mTLS e o erp_token vem
rem automaticamente do ERP (endpoint publico, com rate limit por IP).

setlocal enableextensions enabledelayedexpansion

set "MIRROR=https://turbgate.botbox.info"
set "ERP_BASE_URL=https://www.seucondominio.com.br"
set "SERVER_ADDR=turbgate.botbox.info:7000"

net session >nul 2>&1
if %errorlevel% neq 0 (
    echo Este instalador precisa rodar como administrador.
    pause
    exit /b 1
)

set "CLIENTE_ID=%~1"
if "%CLIENTE_ID%"=="" set /p "CLIENTE_ID=Codigo do cliente: "
if "%CLIENTE_ID%"=="" (
    echo cliente_id vazio.
    exit /b 1
)

set "INSTALL_DIR=%ProgramFiles%\turbgate"
set "DATA_DIR=%ProgramData%\turbgate"
mkdir "%INSTALL_DIR%" 2>nul
mkdir "%DATA_DIR%" 2>nul

echo.
echo Baixando binario...
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
  "Invoke-WebRequest -Uri '%MIRROR%/turbgate_windows_amd64.exe' -OutFile '%INSTALL_DIR%\turbgate.exe' -UseBasicParsing"
if not exist "%INSTALL_DIR%\turbgate.exe" (
    echo Falha ao baixar turbgate.exe
    exit /b 1
)

echo Pedindo cert mTLS no ERP (cliente_id=%CLIENTE_ID%)...
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
  "$body = @{ cliente_id=[int]'%CLIENTE_ID%' } | ConvertTo-Json;" ^
  "$r = Invoke-RestMethod -Method Post -Uri '%ERP_BASE_URL%/portarias/issue_tunnel_cert.json' -Body $body -ContentType 'application/json';" ^
  "Set-Content -Path '%DATA_DIR%\ca.pem'   -Value $r.ca_pem   -Encoding Ascii;" ^
  "Set-Content -Path '%DATA_DIR%\cert.pem' -Value $r.cert_pem -Encoding Ascii;" ^
  "Set-Content -Path '%DATA_DIR%\key.pem'  -Value $r.key_pem  -Encoding Ascii;" ^
  "Set-Content -Path '%DATA_DIR%\erp_token.tmp' -Value $r.erp_token -Encoding Ascii;" ^
  "if ($r.server_addr) { Set-Content -Path '%DATA_DIR%\server_addr.tmp' -Value $r.server_addr -Encoding Ascii }"

if not exist "%DATA_DIR%\cert.pem" (
    echo Falha ao obter cert do ERP.
    exit /b 1
)
if not exist "%DATA_DIR%\erp_token.tmp" (
    echo ERP nao retornou erp_token. Verifique PORTARIA_SERVER_SALT no Rails.
    exit /b 1
)

set /p "ERP_TOKEN=" < "%DATA_DIR%\erp_token.tmp"
del "%DATA_DIR%\erp_token.tmp"

if exist "%DATA_DIR%\server_addr.tmp" (
    set /p "SERVER_ADDR=" < "%DATA_DIR%\server_addr.tmp"
    del "%DATA_DIR%\server_addr.tmp"
)

> "%DATA_DIR%\turbgate.yaml" (
    echo server_addr: %SERVER_ADDR%
    echo cliente_id: %CLIENTE_ID%
    echo cert_file: %DATA_DIR:\=/%/cert.pem
    echo key_file: %DATA_DIR:\=/%/key.pem
    echo ca_file: %DATA_DIR:\=/%/ca.pem
    echo erp_base_url: %ERP_BASE_URL%
    echo erp_token: %ERP_TOKEN%
    echo state_dir: %DATA_DIR:\=/%
    echo log_level: info
)

echo.
echo Registrando servico Windows...
sc.exe stop turbgate >nul 2>&1
sc.exe delete turbgate >nul 2>&1
sc.exe create turbgate binPath= "\"%INSTALL_DIR%\turbgate.exe\" run --config \"%DATA_DIR%\turbgate.yaml\"" start= auto DisplayName= "turbgate client" >nul
sc.exe description turbgate "turbgate reverse tunnel client" >nul
sc.exe failure turbgate reset= 86400 actions= restart/2000/restart/5000/restart/15000 >nul
sc.exe start turbgate

echo.
echo Pronto. cliente_id=%CLIENTE_ID%
echo Logs:    Get-EventLog -LogName Application -Source turbgate
echo Status:  sc.exe query turbgate
endlocal
exit /b 0
