@echo off

set tmpSUM=""

for /f "eol=# tokens=1,2* delims==" %%i in (' findstr "temp_dir" hpsum.ini 2^>NUL') do (set tmpSUM=%%j)
set tmpSUM=%tmpSUM:/=\%

IF %tmpSUM%=="" (
  set tmpSUM=%tmp%
)

set tmp8SUM=""
for /f "eol=# tokens=1,2* delims==" %%i in (' findstr "temp_dir" sum.ini 2^>NUL') do (set tmp8SUM=%%j)
set tmp8SUM=%tmp8SUM:/=\%

IF %tmp8SUM%=="" (
  set tmp8SUM=%LOCALAPPDATA%
)

IF "%1"=="/h" (
  echo syntax: %0 [/y] [/h]
  echo /y = continue without pausing for prompts
  goto :EOF
)

IF "%1"=="/y" (
  set SKIP=1
) ELSE (
  set SKIP=0
)


echo Smart Update Manager cached data delete script
echo                       -
echo Removing SUM cache files will require re-entering
echo all baseline locations, nodes and credentials.
echo                       -
echo This script should not be run while SUM is running.
echo                       -
REM Look for SUM processes.  Returns '0' if found, '1' if not found
tasklist | find "sum_service"
if %errorlevel% EQU 0 (
  echo                       -
  echo ========================================================
  echo WARNING: SUM instances were found currently running.
  echo Please exit SUM using Logout and shutdown from the
  echo browser running SUM or use 'smartupdate shutdownengine'
  echo before calling clean-cache to prevent file conflicts.
  echo ========================================================
  echo                       -
  REM This is now only a warning because it might be a script or other process with sum in the name (SIM)
  REM goto end
  )

IF %SKIP%==1 goto oktodelete
set /p ok="Are you sure you want to delete SUM cache files? [y or n] : "

if "%ok%"=="y" goto oktodelete
echo Exiting without deleting any files.
goto end

:oktodelete
:oktodelete
IF EXIST %tmpSUM%\HPSUM (
CALL :deletelogs "%tmpSUM%" HPSUM hpsum.pdb hpsum.pdb-wal hpsum.pdb-shm hpsum_remote.pdb
)
CALL :deletelogs "%tmp8SUM%" sum sum.pdb sum.pdb-wal sum.pdb-shm sum_remote.pdb

:end
IF %SKIP%==0 (
  pause
)
goto :EOF

:deletelogs
IF EXIST %~1\%2 (

  IF EXIST %~1\%2\baseline (
    echo Removing %~1\%2\baseline
    rmdir /s /Q %~1\%2\baseline
  ) ELSE (
    echo %~1\%2\baseline already deleted.
  )
  
  IF EXIST %~1\%2\uak (
  echo Removing %~1\%2\uak
  del /s /a:h %~1\%2\uak
  )
  
  FOR %%J IN ( %3 %4 %5 %6 %7 ) DO (
     FOR /F "usebackq" %%I in (`dir /s /b %~1\%2 2^>NUL ^| find "%%J" 2^>NUL `) DO (
                echo Removing %%I
                        erase /Q /F %%I
         )
  )

  FOR /F "usebackq" %%P IN (`dir /ad /b %~1\%2 2^>NUL ^| findstr /B /R ._._._. 2^>NUL `) DO (
        echo Removing directory %~1\%2\%%P
        rmdir /S /Q %~1\%2\%%P
  )

) ELSE (
  echo No sum temp directory found to delete. (%~1\%2) 
)

EXIT /B 0


