@echo off
chcp 65001 >nul 2>&1
setlocal enabledelayedexpansion

set "TEMP_DIR=%~dp0"
if "%TEMP_DIR:~-1%"=="\" set "TEMP_DIR=%TEMP_DIR:~0,-1%"

if defined GAMELAUNCHER_DIR (
    set "APP_DIR=%GAMELAUNCHER_DIR%"
) else (
    for %%I in ("%TEMP_DIR%") do set "APP_DIR=%%~dpI"
    if "!APP_DIR:~-1!"=="\" set "APP_DIR=!APP_DIR:~0,-1!"
)

set "EXE_NAME=%GAMELAUNCHER_EXE%"
if not defined EXE_NAME set "EXE_NAME=GameLauncher.exe"

echo Waiting for %EXE_NAME% to exit...

:wait_loop
tasklist /FI "IMAGENAME eq %EXE_NAME%" 2>NUL | find /I /N "%EXE_NAME%">NUL
if not errorlevel 1 (
    timeout /t 1 /nobreak >nul 2>&1
    goto wait_loop
)

echo Applying update...

if not exist "%APP_DIR%" (
    echo ERROR: Application directory not found
    pause
    exit /b 1
)

if not exist "%TEMP_DIR%" (
    echo ERROR: Temp directory not found
    pause
    exit /b 1
)

echo Copying files...
set "ROBOCOPY_SRC=%TEMP_DIR%"
set "ROBOCOPY_DST=%APP_DIR%"
if "%ROBOCOPY_SRC:~-1%"=="\" set "ROBOCOPY_SRC=%ROBOCOPY_SRC:~0,-1%"
if "%ROBOCOPY_DST:~-1%"=="\" set "ROBOCOPY_DST=%ROBOCOPY_DST:~0,-1%"

robocopy "%ROBOCOPY_SRC%" "%ROBOCOPY_DST%" /E /XF update.bat update.bin /R:3 /W:1 /NFL /NDL /NJH /NJS
set "ROBOCOPY_EXIT=%ERRORLEVEL%"
if %ROBOCOPY_EXIT% GEQ 8 (
    echo ERROR: Failed to copy files (exit code: %ROBOCOPY_EXIT%^)
    pause
    exit /b 1
)

set "EXE_FULL_PATH=%APP_DIR%\%EXE_NAME%"
if not exist "%EXE_FULL_PATH%" (
    echo ERROR: Application not found: %EXE_FULL_PATH%
    pause
    exit /b 1
)

echo Update completed successfully!

cd /d "C:\" >nul 2>&1
start "" /D "%APP_DIR%" "%EXE_FULL_PATH%"
if errorlevel 1 (
    echo ERROR: Failed to start application
    pause
    exit /b 1
)

exit /b 0

