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

if not exist "logs" mkdir "logs"

set "BRIDGE_URL=http://127.0.0.1:3480/"
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"
)

if not exist "%NODE_EXE%" (
  echo.
  echo [Bobalive Printer Bridge] Start failed.
  echo Node runtime was not found.
  echo Please download the latest printer bridge package again.
  echo.
  pause
  exit /b 1
)

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.
  echo [Bobalive Printer Bridge] Bridge is already running.
  echo [Bobalive Printer Bridge] Please do not open it twice.
  echo.
  start "" "%BRIDGE_URL%"
  timeout /t 3 /nobreak >nul
  exit /b 0
)

echo [Bobalive Printer Bridge] Starting...
echo Runtime: "%NODE_EXE%"

start "" /min "%~dp0Run-Printer-Bridge.cmd"

timeout /t 2 /nobreak >nul
start "" "%BRIDGE_URL%"

echo.
echo If the browser does not open, open this URL manually:
echo %BRIDGE_URL%
echo.
timeout /t 3 /nobreak >nul
exit /b 0
