@echo off
setlocal
cd /d "%~dp0"

rem Prefer the deployed binary chosen by the auto-update service; manual runs use release\myfile.exe.
set "EXE=%~dp0release\myfile.exe"
if defined AUTOUPDATE_BINARY set "EXE=%AUTOUPDATE_BINARY%"

rem Stop any previously deployed instance under release\ before replacing/starting.
powershell -NoProfile -ExecutionPolicy Bypass -Command "$dir=[IO.Path]::GetFullPath('%~dp0release'); Get-Process -ErrorAction SilentlyContinue | ForEach-Object { try { $p=$_.Path; if ($p -and ([IO.Path]::GetDirectoryName($p) -ieq $dir)) { Write-Host ('[stop] ' + $_.ProcessName + ' (PID ' + $_.Id + ')'); Stop-Process -Id $_.Id -Force -ErrorAction Stop } } catch {} }"

if defined AUTOUPDATE_BINARY (
    if not exist "%EXE%" (
        echo [error] Deployed binary not found: %EXE%
        exit /b 1
    )
) else (
    if exist "%~dp0bin\myfile.exe" (
        if not exist "%~dp0release" mkdir "%~dp0release"
        copy /y "%~dp0bin\myfile.exe" "%EXE%" >nul 2>nul
        if errorlevel 1 (
            ping -n 2 127.0.0.1 >nul
            copy /y "%~dp0bin\myfile.exe" "%EXE%" >nul
        )
        if errorlevel 1 (
            echo [error] Failed to copy bin\myfile.exe to release\.
            exit /b 1
        )
        echo Deployed latest build: bin\myfile.exe -^> release\myfile.exe
    ) else (
        if not exist "%EXE%" (
            echo [error] Neither release\myfile.exe nor bin\myfile.exe exists.
            echo [error] Run build.bat first.
            exit /b 1
        )
    )
)

if not defined admin_token echo [hint] admin_token is not set; upload, mkdir, rename and delete are disabled.

echo Starting %EXE%
"%EXE%" -dir "%~dp0." -addr 127.0.0.1:8080 %*
exit /b %errorlevel%
