@echo off
SETLOCAL EnableExtensions DisableDelayedExpansion
if not "%~1"=="--help" if not "%~1"=="?" if not "%~1"=="/?" goto NoHelp
echo Syntax: wows-restore [_savegame_archive.rar^|_bundle_folder_substring] [noask] [acc^|noacc] [unsafe] [run^|norun]
echo 1) If WoW server is running it will be termintated and then restarted along
echo    with WoW.exe game client.
echo 2) WoW.exe should be manually quit in order to restore saved variables of
echo    Addons from files belonging to account data.
echo ==== Examples ====
echo Restores latest savefile including (by default) account data:
echo    wows-restore
echo Restores latest savefile incl. account data, never restarts server+client:
echo    wows-restore norun
echo Restores from savefile excluding (by default) account data:
echo    wows-restore wows-1.12-632-Kharanos-L27@.rar
echo Same as above but starts server+client even if they were not running:
echo    wows-restore *-632*.rar run
echo Restores from .rar bundle, extracts account data due to 'acc' option:
echo    wows-restore -71- acc
echo Restores the last save listed in .rar bundle, never restarts:
echo    wows-restore "" norun
exit /b 1

:NoHelp
call "%~dp0wows-where.cmd" tasklist.exe taskkill.exe rar.exe& if errorlevel 1 exit /b 1

set FOLDER=
set SAVEFILE=
set "WHAT=%~1"
SETLOCAL EnableDelayedExpansion
if /I "!WHAT:~-4!"==".rar" FOR %%F in ("!WHAT!") DO if exist "%%~fF" ENDLOCAL& set "SAVEFILE=%%~fF"& shift /1& goto FoundSpecified
ENDLOCAL
FOR %%N IN ("" noask acc noacc unsafe run norun) DO if '%1'=='%%~N' goto ScanForLatest

REM arc.exe a -r -rr -m9 -mct- -ld128m -dsnt -tl "..\wows-3.3.5a--bundle@.arc"
REM produces MUCH smaller archive than RAR5 (2176k vs 8793k)
set "SAVEFILE=%WOWDIR%\wows-%WOWVER%--bundle@.arc"
if exist "%SAVEFILE%" FOR /F "delims=" %%L IN ('arc lb "%SAVEFILE%" -- "*%~1*\WTF\Config.wtf"') DO set "FOLDER=%%L"& call set FOLDER=%%FOLDER:~0,-15%%
if not defined FOLDER set "SAVEFILE=%WOWDIR%\wows-%WOWVER%--bundle@.rar"
echo Bundle is "%SAVEFILE%"
if not defined FOLDER if exist "%SAVEFILE%" FOR /F "delims=" %%L IN ('rar lb "%SAVEFILE%" "*%~1*\WTF"') DO set FOLDER=%%L& call set FOLDER=%%FOLDER:~0,-4%%
if not defined FOLDER goto NotFound
shift /1
set "FOLDER=%FOLDER%\"
echo Found save folder: %FOLDER%
echo Bundle: %SAVEFILE%
if _%1==_noask shift /1& goto FoundSpecified
echo Press Space to RESTORE server databases from it or CtrlBreak to QUIT ...& pause>nul

:FoundSpecified
if /I not _%1==_acc if /I not _%1==_noacc goto SkipAccount
goto CheckAccount
:NotFound
echo FATAL! Save file %1 not found!& pause>nul
exit /b 1

:ScanForLatest
set SAVEFILE=1000
for /L %%n in (99,-1,1) DO (
 for %%F in ("wows-%WOWVER%-%%n???@.rar" "wows-%WOWVER%-%%n???-*@.rar") DO set /A SAVEFILE=%%n000+1000& goto FoundLimit
)
:FoundLimit
for /L %%n in (%SAVEFILE%,-1,1) DO (
 for %%F in ("wows-%WOWVER%-%%n@.rar?" "wows-%WOWVER%-%%n-*@.rar") DO set "SAVEFILE=%%~fF"&goto FoundLatest
)
echo FATAL! No save file(s) found! "wows-%WOWVER%-<number>[-<description>]@.rar"& pause>nul
exit /b 1
:FoundLatest
echo Latest save file: %SAVEFILE%
if _%1==_noask shift /1& goto CheckAccount
echo Press Space to RESTORE server databases from it or CtrlBreak to QUIT ...& pause>nul

:CheckAccount
if /I _%1==_noacc shift/1& goto SkipAccount
if /I _%1==_acc shift/1
%TASKKILL_FORCE% WoW.exe &REM ради правильной работы "подсчитывающих" аддонов, которую могут сбивать несинхронизированные перезагрузки
REM К сожалению, taskkill.exe не понимает маршрутов, иначе лучше бы "%WOWDIR%\WoW.exe"
echo Removing "%CD%\WTF\Account\A\"
:TryAccRD
rd /s /q "WTF\Account\A" &REM ...безопасно ли предварительно удалять все наличные файлы настроек?
if exist "WTF\Account\A" echo ERROR! rmdir "WTF\Account\A"& ping -n 1 -l 2 -w 300 127.255.255.255 >nul & goto TryAccRD
echo on
if /I not "%SAVEFILE:~-4%"==".arc" goto SkipArc1
arc x -y -ap="%FOLDER%WTF\Account" -dp="WTF\Account" "%SAVEFILE%"
@goto SkipRar1
:SkipArc1
rar x -idc -y -ep1 "%SAVEFILE%" "%FOLDER%WTF\Account\*" WTF\Account\
:SkipRar1
@echo off
if errorlevel 1 echo Warning! cannot unpack WTF\Account. Press any key to continue...& pause>nul
:SkipAccount

set RESTORESERVER=
REM Если взять вещи из банка Гильдии и затем перегрузиться unsafe, то этих вещей в банке не будет, т.е. состояние банка считывается из БД только при запуске сервера (хотя пишется постоянно)
if /I _%1==_unsafe goto SkipStop

for %%I in ("%COMSPEC%") do %FOR_TASKLIST% DO (
  SETLOCAL EnableDelayedExpansion
  set WHAT=%%~L
  if defined WHAT set WHAT=!WHAT:  = !& set WHAT=!WHAT:*: =!
  if "!WHAT!"=="authserver for WoW" (ENDLOCAL& set RESTORESERVER=yes) else ENDLOCAL
)
call .\wows-stop.cmd keepsql wait
:SkipStop
call .\wows-run.cmd sqlonly

pushd "%BASEDIR%\"
if exist "%TMP%\auth_characters.sql" del "%TMP%\auth_characters.sql"
if exist "%TMP%\auth_characters.sql" popd& echo FATAL! cannot remove colliding "%TMP%\auth_characters.sql" ...& pause>nul& exit /b 1
echo on
@if /I not "%SAVEFILE:~-4%"==".arc" goto SkipArc2
arc x -y -x*\* -ap="%FOLDER%\" -dp="%TMP%" "%SAVEFILE%" auth_characters.sql
@goto SkipRar2
:SkipArc2
rar x -idc -y -ep1 -x"%FOLDER%WTF" "%SAVEFILE%" "%FOLDER%auth_characters.sql" "%TMP%"\
:SkipRar2
@echo off
if not exist "%TMP%\auth_characters.sql" popd& echo FATAL! cannot unpack "auth_characters.sql" ...& pause>nul& exit /b 1
_MySQL\bin\mysql.exe --user=root --password=ascent <"%TMP%\auth_characters.sql"
if errorlevel 1 popd& echo FATAL! loading DBs from "%TMP%\auth_characters.sql" ...& pause>nul& exit /b 1
echo Done: reloaded databases `auth` and `characters`
del "%TMP%\auth_characters.sql"
popd
if /I _%1==_unsafe if not _%2==_run exit /b 0
if /I not _%1==_run if not defined RESTORESERVER exit /b 0
if /I not _%1==_norun wows-run.cmd
