#! /bin/sh

# Remove the release directory chosen by the user.
# This script must be stored in all <repository root>\dists\<product>\<package group> 
# directories.  It finds and displays the list of release directories in this
# directory and enables the user to select the desired release directory to be removed.
# NOTE: grep and awk must be installed as this script utilizes them

baseDir=`dirname $0`
baseName=`basename $0`
selectedRelDir=$1
listOptions=1

# return values from boolean functions
# ( 0/"success" is interpreted as "true" in scripts )
TRUE=0
FALSE=1

isValidRelDir()
{
	if [ ! -z "$1" ] && \
	   [ -d "$1" ] && \
	   [ "$1" != "current" ] && \
	   [ -f "$1/release.txt" ] && \
	   [ -f "$1/release.sig" ] && \
	   [ -f "$1/packages.txt" ]; then 
		return $TRUE
	fi
	return $FALSE
}

isCurrentRel()
{
	if isValidRelDir $1 && \
	   [ -f "current/release.txt" ]; then 
	   	givenrel=`cat $1/release.txt`
	   	currel=`cat current/release.txt`
		if [ "$givenrel" == "$currel" ]; then
			return $TRUE
		fi
	fi
	return $FALSE
}

# return the list of release dirs in the current dir
getRelDirList()
{
	dirList=""
	for entry in `ls` ; do
		if isValidRelDir "$entry" ; then
		   dirList="$dirList $entry"
		fi
	done
	echo $dirList
}

# Change to the directory where this script is located, which should be
# the <repository root>\dists\<product>\<package group> directory
cd "$baseDir"

if [ ! -z "$selectedRelDir" ]; then
	if isValidRelDir "$selectedRelDir" ; then
		if ! isCurrentRel "$selectedRelDir" ; then
			for entry in `getRelDirList` ; do
				if [ "$entry" != "$selectedRelDir" ]; then
					pkgKeepLst="$pkgKeepLst `cat $entry/packages.txt | grep Filename: | awk '{print $2}'`"
				fi
			done
			for pkg in `cat $selectedRelDir/packages.txt | grep Filename: | awk '{print $2}'` ; do
				echo $pkgKeepLst | grep -w $pkg > /dev/null
				if [ $? -ne 0 ]; then
					rm -rf ../../../pool/$pkg
					echo Removed $pkg
				fi
			done
			rm -rf $selectedRelDir
			echo "Release $selectedRelDir removed from repository."
			exit 0
		fi
	else
		echo
		echo "ERROR: Release $selectedRelDir is not a valid option.  Try again."
		echo
	fi
fi

if [ "$listOptions" -eq 1 ]; then
	# List all of the release directories in the current directory.
	echo
	echo "Removable Release Options:"
	for entry in `getRelDirList` ; do
		if isCurrentRel "$entry" ; then
			curRel=$entry
		else
			echo "  $entry"
		   	expRelDir=$entry
		fi
	done

	if [ -z "$expRelDir" ]; then
		echo "  No removable releases options found"
		if [ -z "$curRel" ]; then
			echo
			exit 1
		fi
	fi

	if [ ! -z "$curRel" ]; then
		echo
		echo "Release $curRel is set as the current release, so it is currently not a valid option for removal."
		if [ -z "$expRelDir" ]; then
			echo
			exit 1
		fi
	fi

	echo
	echo "To remove a release from this repository, re-run $baseName with desired Release Options above."
	echo "  Example: $0 $expRelDir"
	echo
fi
