@echo off

setlocal
pushd "%~dp0"

:GetDate
:: Credit to SS64.com Code taken from http://ss64.com/nt/syntax-getdate.html
:: Use WMIC to retrieve date and time in ISO 8601 format.
for /f "skip=1 tokens=1-6" %%G in ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') do (
    if "%%~L"=="" goto s_done
    set _yyyy=%%L
    set _mm=00%%J
    set _dd=00%%G
    set _hour=00%%H
    set _minute=00%%I
)
:s_done
:: Pad digits with leading zeros
set _mm=%_mm:~-2%
set _dd=%_dd:~-2%
set _hour=%_hour:~-2%
set _minute=%_minute:~-2%
set iso_date=%_yyyy%-%_mm%-%_dd%

rem Get uninstaller path from registry
set "uninstaller="
for /f usebackq^ tokens^=2^ delims^=^" %%s in (
	`reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{35065F43-4BB2-439A-BFF7-0F1014F2E0CD}_is1" /v UninstallString`
) do (
	set "uninstaller=%%s"
)

rem Copy logs to 1201 folder
echo "Copying logs..."
robocopy /e "%PROGRAMDATA%\Malwarebytes\MBAMService\LOGS" "%SYSTEMDRIVE%\1201\Logs\%iso_date%\Tools\MBAM" >nul
robocopy /e "%PROGRAMDATA%\Malwarebytes\MBAMService\ScanResults" "%SYSTEMDRIVE%\1201\Logs\%iso_date%\Tools\MBAM" >nul

if exist "%SYSTEMDRIVE%\1201\Preserve-MBAM.marker" (
	rem Keep MBAM
	echo Previous Malwarebytes installation detected.
) else (
    rem Move Quarantine to 1201 folder
    move "%PROGRAMDATA%\Malwarebytes\Malwarebytes Anti-Malware\Quarantine" "%SYSTEMDRIVE%\1201\Quarantine\MBAM_%iso_date%_%_hour%%_minute%"
    
	rem Remove MBAM
	echo No previous Malwarebytes installation detected.
	if exist "%uninstaller%" (
		echo "Uninstalling Malwarebytes..."
		start "" /wait "%uninstaller%" /VERYSILENT /NORESTART /LOG
	) else (
		color 4e
		echo "Malwarebytes installation not found."
		echo ""
		echo "Press any key to exit... "
		pause >nul
	)
)

rem Remove marker
del /f "%SYSTEMDRIVE%\1201\Preserve-MBAM.marker"

popd
endlocal