taskkill /f /im AppMarket.exe /t

rmdir "%~dp0ICafeCloud\ProgramData\Tencent\TxGameAssistant\Log" /S /Q 2>nul

mkdir "%LocalAppData%\Tencent" 2>nul
mkdir "%ProgramData%\Tencent" 2>nul
mkdir "%AppData%\Tencent" 2>nul

rem ==== Redirect live Tencent user data to the persistent idc payload, ICafeCloud\, via junctions ====
rem Data-safe: if the backup target is missing, real live data is moved into it first; the live dir is
rem only removed once a valid backup exists, so this never deletes data and never leaves a dangling link.
call :gameloop_link "%LocalAppData%\Tencent\TxGameAssistant" "%~dp0ICafeCloud\LocalAppData\Tencent\TxGameAssistant"
call :gameloop_link "%LocalAppData%\Tencent\QQGuild"         "%~dp0ICafeCloud\LocalAppData\Tencent\QQGuild"
call :gameloop_link "%ProgramData%\Tencent\qimei"            "%~dp0ICafeCloud\ProgramData\Tencent\qimei"
call :gameloop_link "%ProgramData%\Tencent\QQPCMgr"          "%~dp0ICafeCloud\ProgramData\Tencent\QQPCMgr"
call :gameloop_link "%ProgramData%\Tencent\TxGameAssistant"  "%~dp0ICafeCloud\ProgramData\Tencent\TxGameAssistant"
call :gameloop_link "%AppData%\Tencent\MobileGamePC"         "%~dp0ICafeCloud\AppData\Roaming\Tencent\MobileGamePC"
call :gameloop_link "%AppData%\Tencent\Androws"              "%~dp0ICafeCloud\AppData\Roaming\Tencent\Androws"

rem ==== Import registry snapshot exported by gamefixes/Gameloop/server.bat ====
rem iCafeCloud Server runs that gamefix server.bat with {gameworkpath} pointing at this same game
rem directory, so the exported .reg files land right here next to AppMarket.exe - read them with
rem %~dp0, no network share needed. Versions/paths come from whatever server.bat last exported.
if exist "%~dp0Tencent.reg" reg import "%~dp0Tencent.reg"
if exist "%~dp0Tencent2.reg" reg import "%~dp0Tencent2.reg"
if exist "%~dp0Uninstall.reg" reg import "%~dp0Uninstall.reg"
if exist "%~dp0Classes_apk.reg" reg import "%~dp0Classes_apk.reg"
if exist "%~dp0Classes_protocol.reg" reg import "%~dp0Classes_protocol.reg"

goto :eof

rem ---- gameloop_link subroutine: %1 = live path, %2 = backup path - data-safe, idempotent ----
:gameloop_link
if exist "%~2" goto :gameloop_link_do
rem backup missing -> seed it so the junction never dangles
fsutil reparsepoint query "%~1" >nul 2>&1 && ( mkdir "%~2" & goto :gameloop_link_do )
if exist "%~1" ( robocopy "%~1" "%~2" /E /XJ /R:1 /W:1 /MOVE /NFL /NDL /NJH /NJS /NP >nul 2>&1 & goto :gameloop_link_do )
mkdir "%~2"
:gameloop_link_do
if exist "%~1" rmdir "%~1" /S /Q 2>nul
mklink /J "%~1" "%~2" >nul
goto :eof
