@echo off
setlocal
cd /d "%~dp0"

if not exist "logs" mkdir "logs"

set "BRIDGE_PORT=3480"

set "NODE_EXE=%~dp0runtime\node.exe"
if not exist "%NODE_EXE%" (
  for %%I in (node.exe) do set "NODE_EXE=%%~$PATH:I"
)

powershell -NoProfile -ExecutionPolicy Bypass -Command "if (Get-NetTCPConnection -LocalPort %BRIDGE_PORT% -State Listen -ErrorAction SilentlyContinue) { exit 0 } else { exit 1 }" >nul 2>nul
if "%errorlevel%"=="0" (
  echo [%date% %time%] Bridge already running on port %BRIDGE_PORT%, skip duplicate start.>>"logs\printer-bridge.log"
  exit /b 0
)

if not defined DISABLE_OPEN_BROWSER set "DISABLE_OPEN_BROWSER=1"
set "SERVER_ENTRY=src\desktop-server.js"
if exist "%~dp0dist-obf\src\desktop-server.js" set "SERVER_ENTRY=dist-obf\src\desktop-server.js"
"%NODE_EXE%" "%SERVER_ENTRY%" 1>>"logs\printer-bridge.log" 2>>&1
