@echo off
SETLOCAL EnableExtensions DisableDelayedExpansion
if not "%~1"=="--help" if not "%~1"=="?" if not "%~1"=="/?" goto NoHelp
echo Performs initial patch or restore+patch procedure for unpacked repack
echo Can perform SQL requests given via cmdline, .sql file or .7z'ipped .sql files
echo Examples:
echo   wows-patch
echo   wows-patch initial
echo   wows-patch unpatch
echo   wows-patch SELECT * FROM player_xp_for_level ^>q:\wow-xp.lst
echo   wows-patch "USE characters; SELECT name,level FROM characters WHERE level>1"
echo   wows-patch : world_ytdb request.sql ^>q:\results.lst
exit /b 1

:NoHelp
if '%1'=='' if defined FARLANG set FARLANG=& start cmd /c; %0 %*& goto :EOF
call "%~dp0wows-where.cmd" 7z.exe repls.exe& if errorlevel 1 goto Err
set "MYOP=%BASEDIR%\_MySQL\bin\mysql.exe --user=root --password=ascent --default-character-set=utf8"
set "MYCHK=& @if errorlevel 1 echo MySQL ERROR! Press any key to continue...& pause>nul"
set WORLD=%1
if _%1==_: (set WORLD=%2& shift /1 & shift /1& echo CREATE DATABASE IF NOT EXISTS %2 DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; | %MYOP% %MYCHK%) else if exist "%BASEDIR%\_MySQL\data\mangos\*" (set WORLD=mangos) else (SET WORLD=world)

set OPBODY=%1
if not defined OPBODY goto Unpatch
if /I "%~1"=="unpatch" goto Unpatch
if /I "%~1"=="initial" call .\wows-stop.cmd keepsql wait& goto DoPatch
call .\wows-run.cmd sqlonly wait
if /I "%~x1"==".sql" goto SqlFile
if /I "%~x1"==".7z" goto Sql7zFile
set OPBODY=%2
if defined OPBODY set OPBODY=%*
if not defined OPBODY set "OPBODY=%~1"
SETLOCAL EnableDelayedExpansion
echo !OPBODY! >"%TEMP%\$wows.tmp.sql"
%MYOP% %WORLD% -v <"%TEMP%\$wows.tmp.sql"
exit /b
:SqlFile
echo on
@if "%~z1"=="" echo ERROR! Cannot find "%1" from folder "%CD%" ...& goto Err
@if %~z1 GEQ 100000 goto BigSql
%MYOP% %WORLD% -v -v <%1 %MYCHK%
@exit /b
:BigSql
%MYOP% %WORLD% <%1 %MYCHK%
@exit /b
:Sql7zFile
echo on
7z x -so %1 | %MYOP% %WORLD% %MYCHK%
@exit /b


:GetRepackID
set "WHAT=%BASEDIR:/=\%"
:StripDir
set "WHAT=%WHAT:*\=%"
if not "%WHAT%"=="%WHAT:*\=%" goto StripDir
exit /B


:AlterWoWExePatch
REM Модификация, умножающая XP за Elite существ
repls -q -w [0x85h][0xc0][0x74][0x07][0x83][0xF8][0x04][0x74][0x02][0x03][0xff] [0x85][0xc0][0x74][0x07][0x8d][0x3c][0xbd][0][0][0][0] --4XP "%BASEDIR%\mangosd.exe"
REM repls -q -w [0x85h][0xc0][0x74][0x07][0x83][0xF8][0x04][0x74][0x02][0x03][0xff] [0x85][0xc0][0x74][0x07][0x8d][0x3c][0xbf][0x90][0x90][0x90][0x90] --5XP "%BASEDIR%\mangosd.exe"
REM repls -q -w [0x85h][0xc0][0x74][0x07][0x83][0xF8][0x04][0x74][0x02][0x03][0xff] [0x85][0xc0][0x74][0x07][0x8b][0xc7][0x8d][0x04][0xb8][0x03][0xF8] --6XP "%BASEDIR%\mangosd.exe"
REM repls -q -w [0x85h][0xc0][0x74][0x07][0x83][0xF8][0x04][0x74][0x02][0x03][0xff] [0x85][0xc0][0x74][0x07][0x8d][0x3c][0xfd][0][0][0][0] --8XP "%BASEDIR%\mangosd.exe"

if %ERRORLEVEL% LSS 0 echo ERROR! Cannot execute repls.exe& goto Err
if %ERRORLEVEL% GEQ 251 echo ERROR! Cannot patch mangosd.exe& goto Err
if not %ERRORLEVEL% EQU 1 echo ERROR! Elite mobs XP patch for mangosd.exe failed...& goto Err

REM Модификация для устранения ошибочного отображения требуемых уровней
REM у наставников Druid:Feral Combat
repls -q -w [0x8B][0x45][0x14][0x85][0xC0][0x75][0x03] [0x8B][0x45][0x14][0x85][0xC0][0x90][0x90] "%BASEDIR%\mangosd.exe"
if not "%ERRORLEVEL%"=="1" echo ERROR! "Trainer" patch for mangosd.exe failed...& goto Err

REM Модификация, чтобы вызов Pet'а Hunter'а не уничтожал личности Minion'ов Warlock'а
repls -q -w "DELETE FROM character_pet WHERE owner = ? AND (slot = ? OR slot > ?)" "DELETE FROM character_pet WHERE owner=? && PetType=1 && slot&?+?+1=0" "%BASEDIR%\mangosd.exe"
if not "%ERRORLEVEL%"=="1" echo ERROR! "Save Pet" patch for mangosd.exe failed...& goto Err

REM Модификация, чтобы вместо Pet'ов Hunter'а не вызывались Minion'ы Warlock'а
repls -q -w "FROM character_pet WHERE owner = '%%u' AND (slot = '%%u' OR slot > '%%u') " "FROM character_pet WHERE owner='%%u' AND slot IN (0,100) AND PetType=1  " "%BASEDIR%\mangosd.exe"
if not "%ERRORLEVEL%"=="1" echo ERROR! "Load Pet" patch for mangosd.exe failed...& goto Err

REM Разрешить всем классам, при наличии умения Pick Pocket, не только смотреть loot, но и брать его
repls -q -w [0xe8][0x99][0x69][0xd1][0xff][0x3c][0x04][0x75][0x10] [0xe8][0x99][0x69][0xd1][0xff][0x3c][0x04][0x90][0x90] "%BASEDIR%\mangosd.exe"
if not "%ERRORLEVEL%"=="1" echo ERROR! "All classes can Pickpocket" patch 1/3 for mangosd.exe failed...& goto Err
repls -q -w [0xe8][0x4d][0x65][0xd1][0xff][0x3c][0x04][0x75][0x10] [0xe8][0x4d][0x65][0xd1][0xff][0x3c][0x04][0x90][0x90] "%BASEDIR%\mangosd.exe"
if not "%ERRORLEVEL%"=="1" echo ERROR! "All classes can Pickpocket" patch 2/3 for mangosd.exe failed...& goto Err
repls -q -w [0xe8][0x6e][0x5b][0xd1][0xff][0x3c][0x04][0x75][0x10] [0xe8][0x6e][0x5b][0xd1][0xff][0x3c][0x04][0x90][0x90] "%BASEDIR%\mangosd.exe"
if not "%ERRORLEVEL%"=="1" echo ERROR! "All classes can Pickpocket" patch 3/3 for mangosd.exe failed...& goto Err

REM Приходится перезапускать лишний раз, иначе в WoW-1.12-AlterWoW-3.5 падает
REM MySQL (возможно, из-за стёртых InnoDB .log файлов; надо сменить версию MySQL)
call .\wows-run.cmd sqlonly
call .\wows-stop.cmd wait
exit /B




:Unpatch
echo Unpatching WoW Server...
call .\wows-stop.cmd wait
pushd "%BASEDIR%\_MySQL\data\%WORLD%"
if exist creature_template.MYD (del /q *.*) else echo ERROR! Not Found MySQL\data\%WORLD%\*& goto Err
echo Extracting from repack archive...
call :GetRepackID
start /w /min 7z e -y "%WOWDIR%\repack\WowServerRepacks.7z" "%WHAT%\_MySQL\data\%WORLD%\*"
REM start /w /min 7z e -y "%WOWDIR%\repack\WowServerRepacks.7z" "%WHAT%\mangosd.exe" "%WHAT%\_MySQL\data\%WORLD%\*"
REM echo Moving server executable...
REM move /y mangosd.exe "%BASEDIR%\"
popd
if /I "%~1"=="unpatch" echo Stopped after unpatching& exit /b 0

:DoPatch
set SQLEXTR=*.sql
for %%F in ("%BASEDIR%\mangosd.exe") do if "%%~zF"=="5237248" set "SQLEXTR=-x!*eventai* *.sql"& call :AlterWoWExePatch
REM if exist WDB\* cd WDB & if not errorlevel 1 rd 2>nul /q /s "..\WDB" & cd ..
if not "%BASEDIR:Nostalrius=%"=="%BASEDIR%" set SQLEXTR=game_tele.sql
call .\wows-run.cmd sqlonly

call :GetRepackID
set "WHAT=%WHAT:*-=%"
set "WHAT=#%WHAT:*-=%"
if not exist "%WHAT%\*" goto SkipUpddir
REM Директория дополнительных/временных .sql обновлений и изменённых .exe/.dll, например D:\Games\WoW-112\#cMangos\ для WoW-1.12-cMangos (название сборки)
if "%~1"=="INITIAL" FOR %%F in ("%WHAT%\*") DO if exist "%BASEDIR%\%%~nxF" (copy /Y "%%~F" "%BASEDIR%\%%~nxF"&& echo Note: Replaced "%BASEDIR%\%%~F"  with "%WHAT%\%%~F") || (echo ERROR! Cannot overwrite "%BASEDIR%\%%~F"  with "%WHAT%\%%~F" ...& pause>nul)
FOR /F "tokens=1* delims=" %%F IN ('dir /b /one "%WHAT%\*_*.sql" 2^>nul') DO @echo %%F& %MYOP% %WORLD% <"%WHAT%\%%~F" %MYCHK%
:SkipUpddir

@echo on
@REM Если нужна перезагрузка БД dbcdata, надо вручную удалить эту БД перед запуском этого .cmd
if exist "repack\dbcdata-%WOWVER%.sql.7z" if not exist "%BASEDIR%\_MySQL\data\dbcdata\*" ((echo CREATE DATABASE IF NOT EXISTS dbcdata;|%MYOP%) && (7z e -so "repack\dbcdata-%WOWVER%.sql.7z" |%MYOP% dbcdata)) %MYCHK%

if not "%BASEDIR:1.12-cMangos=%%BASEDIR:AlterWoW=%%BASEDIR:Nostalrius=%%BASEDIR:Sunwell=%"=="%BASEDIR%%BASEDIR%%BASEDIR%%BASEDIR%" ^
if exist "repack\worldpatch-%WOWVER%.sql.7z" 7z e -so "repack\worldpatch-%WOWVER%.sql.7z" %SQLEXTR% |%MYOP% %WORLD% %MYCHK%

if "%BASEDIR:1.12-cMangos=%%BASEDIR:AlterWoW=%%BASEDIR:Sunwell=%%BASEDIR:Jeutie=%"=="%BASEDIR%%BASEDIR%%BASEDIR%%BASEDIR%" goto Done
if not exist "patch-%WOWVER:.=%.php" goto Done
if not exist "%BASEDIR%\patch-%WOWVER:.=%.0.log" ren "%BASEDIR%\patch-%WOWVER:.=%.log" *.0.log
call php "patch-%WOWVER:.=%.php" >"%BASEDIR%\patch-%WOWVER:.=%.log"
@if errorlevel 1 echo ERROR! "patch-%WOWVER:.=%.php" - check "%BASEDIR%\patch-%WOWVER:.=%.log" ...& echo off& goto Err
:Done
@echo off
exit /b 0
:Err
pause>nul& exit /b 1
