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

set "PROGRAM_FILE=%~dp0program\x64dbg-unsigned.exe"

if not exist "%PROGRAM_FILE%" goto missing_file

echo Stopping previous x64dbg-unsigned.exe process...
taskkill /F /T /IM "x64dbg-unsigned.exe" >nul 2>&1

echo Starting...
start "" "%PROGRAM_FILE%"
goto wait_ready

:wait_ready
rem Prefer curl for a real HTTP request. It exits 0 for any HTTP response.
curl.exe --silent --output NUL --connect-timeout 1 --max-time 2 --noproxy "*" "http://127.0.0.1:34291/" >nul 2>&1
if not errorlevel 1 goto ready

rem Fallback for systems without curl. EndConnect is the reliable success check.
powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "$tcp = New-Object System.Net.Sockets.TcpClient; try { $async = $tcp.BeginConnect('127.0.0.1', 34291, $null, $null); if (-not $async.AsyncWaitHandle.WaitOne(2000)) { exit 1 }; $tcp.EndConnect($async); exit 0 } catch { exit 1 } finally { $tcp.Close() }" >nul 2>&1
if not errorlevel 1 goto ready

echo waiting
timeout /t 1 /nobreak >nul
goto wait_ready

:ready
echo ready
goto done

:missing_file
echo ERROR: File does not exist: %PROGRAM_FILE%
pause

:done
endlocal
