@echo OFF
setlocal enabledelayedexpansion

cls
echo ---------------------------------------
echo --- unipatch v0.8 by epithetic --------
echo ---------------------------------------
echo.
echo.

set "dest=%1"
set "work=%~dp0%"
rem Default destination to working directory
if %1.==. set "dest=%~dp0%"

if not exist unip-backup\ goto MissingDir

set warncount=0
set errcount=0

echo.

echo Preparing to revert all unip patches...
echo.

echo ---------------------------------------- >> unipatch-log.txt
echo %time% %date% ^| Reverting all changes to !dest! >> unipatch-log.txt
echo ---------------------------------------- >> unipatch-log.txt
echo. >> unipatch-log.txt

rem Remove spaces from paths so it's easier to wrangle relative paths
set work_=!work: =█!
set dest_=!dest: =█!

echo copying files...
rem Overwrite files with backups
xcopy /s /f /y "unip-backup" "!dest!" >> unipatch-log.txt

rem Read unip deletelog
if exist unip-backup\delete.log (
	for /F "usebackq tokens=*" %%A in ("unip-backup\delete.log") do (
		set deletepath_=%%A
		set "deletepath=!deletepath_:█= !"
		if exist !dest!!deletepath! (
			echo deleting !deletepath!...
			del "!dest!!deletepath!"
		) else (
			rem Missing delete file
			echo "Warning: !deletepath! was slated for deletion, but missing.
			echo WARNING: !dest!!deletepath! was slated for deletion, but could not be found. >> unipatch-log.txt
			set /a warncount+=1
		)
		
	)
)
rem Remove deletelog now that we're done and delete backup folder
del unip-backup\delete.log
if exist !dest!delete.log (
	del "!dest!delete.log"
)

@rd /s /q "unip-backup"
del unipatch-installed.txt

echo.
echo Finished reverting all unip patches with !warncount! warnings and !errcount! errors.

goto End


:MissingDir
echo There doesn't appear to be a backup directory, cannot revert changes.
goto End

:End
goto :eof

:ReplaceText
::Replace Text In String
:: call:ReplaceText "!OriginalText!" OldWordToReplace NewWordToUse  Result
set "OriginalText=%~1"
set "OldWord=%~2"
set "NewWord=%~3"
call set OriginalText=%%OriginalText:!OldWord!=!NewWord!%%
set %4=!OriginalText!
goto End