@echo off
rem  Remove the release directory chosen by the user.
rem  This script must be stored in all <repository root>\dists\<product>\<package group> 
rem  directories.  It finds and displays the list of release directories in this
rem  directory and enables the user to select the desired release directory to be removed.

setlocal EnableDelayedExpansion

set origDir=%CD%
set baseDir=%~dp0%
set cancelKey=C
set pkgKeepLst=pkgKeepLst.tmp

rem Change to the directory where this script is located, which should be
rem the <repository root>\dists\<product>\<package group> directory
cd /d %baseDir%

rem Find all of the release directories in the current directory.
set numRelDirs=0
for /d %%a in (*) do (
	if not %%a == current (
		if exist %%a\release.txt (
			if exist %%a\release.sig (
				if exist %%a\packages.txt (
					fc %%a\release.txt current\release.txt >nul
					if "!ERRORLEVEL!" == "0" (
						set curRel=%%a
					) else (
						set relDirs=!relDirs! %%a
						set /a numRelDirs+=1
)	)	)	)	)	)

if "%relDirs%" == "" (
	@echo No removable release options found
	if not "%curRel%" == "" (
		@echo Release %curRel% is set as the current release, so it is currently not a valid option for removal.
	)
	goto end
)

rem Create and display a menu of release directories from which the user
rem will choose to set as the current release.
:userprompt
echo.
@echo Key    Removable Release Options
set i=0
for %%a in (%relDirs%) do (
	@echo !i!      %%a
	set /a i+=1
)
@echo %cancelKey%      Cancel
if not "%curRel%" == "" (
	echo.
	@echo Release %curRel% is set as the current release, so it is currently not a valid option for removal.
)
echo.
set /p selection="Select the Key corresponding to the desired Removable Release Option to remove or Cancel. "

if "%selection%" == "%cancelKey%" (
	@echo Exiting with no Release Directory removed.
	goto end
)

if "%selection%" GEQ "0" (
	if "%selection%" LSS "%numRelDirs%" (
		set i=0
		for %%a in (%relDirs%) do (
			if "!i!"=="%selection%" (
				set selectedDir=%%a
				goto removeIt
			)
			set /a i+=1
		)
:removeIt		
		if "%selectedDir%" == "" (
			goto error
		)
		if exist %pkgKeepLst% (
			del %pkgKeepLst%
		)
		for %%a in (%relDirs% %curRel%) do (
			if not "%%a" == "%selectedDir%" (
				for /f "usebackq tokens=2" %%b in (`"findstr /r ^Filename: %%a\packages.txt"`) do (
					@echo %%b >> %pkgKeepLst%
				)
			)
		)
		for /f "usebackq tokens=2" %%b in (`"findstr /r ^Filename: %selectedDir%\packages.txt"`) do (
			findstr %%b %pkgKeepLst% > nul
			if not "!ERRORLEVEL!" == "0" (
				del ..\..\..\pool\%%b
				@echo Removed %%b
			)
		)
		rmdir /s /q %selectedDir%
		@echo Release %selectedDir% removed from repository.
		goto end
)	)

:error
echo.
@echo ERROR: "%selection%" is not a valid Key, try again.
echo.
goto userprompt

:end
if exist %pkgKeepLst% (
	del %pkgKeepLst%
)

cd %origDir%

endlocal
