#!/bin/sh
# Copyright (C) 2014 - 2018 FARGOS Development, LLC
# Remove/identify unmodified files which are provided by a backing tree
# and already maintained in Subversion.
# Used to cleanup a sandbox when too many files were checked out.
# $Id$
# Depends upon findFileinSB

force=0
fileList=""
quiet=0
while test $# -gt 0
do
	case "${1}" in
	-h | -help | --help)
		printf "%s: [--force] -[q] [-l] [-k] file/dir [...]\n" "${0}" >&2
		printf "  -l[ist] = list files that should be deleted\n" >&2
		printf "  -k[eep] = list files that should be retained\n" >&2
		printf "  -q[uiet] = silent operation\n";  >&2
		exit 1
		;;
	-force | --force)
		force=1
		;;
	-q | -quiet | --quiet)
		quiet=1
		;;
	-l | -list | --list)
		quiet=2
		;;
	-k | -keep | --keep)
		quiet=3
		;;
	*)
		fileList="${fileList}${fileList:+ }${1}"
		;;
	esac
	shift
done
onlyFiles=""
for entry in ${fileList} # expand directory references into files
do
	if test -f ${entry} #
	then
		onlyFiles="${onlyFiles}${onlyFiles:+ }${entry}"
	elif test -d ${entry} # a directory
	then
		fileList=`find ${entry} -type f -print`
		onlyFiles="${onlyFiles}${onlyFiles:+ }${fileList}"
	fi
done

# now for each file
possiblyRemove=""
for entry in ${onlyFiles}
do
	case "${entry}" in
	*/\.svn/*) # Ignore ${entry} as it's an SVN data file
		continue
		;;
	esac
	statusResult=`svn status ${entry} 2>&1`
	if test -z "${statusResult}"
	then
		if test ${force} -eq 0
		then
			btCopy=`findFileInSB -allbt ${entry}`
			if test -z "${btCopy}"
			then
				if test ${quiet} -eq 0
				then
					printf "Retaining %s as no backing tree copy exists.\n" "${entry}"
				fi
				continue
			fi
			different=`diff -q ${btCopy} ${entry}`
			if test -n "${different}"
			then
				if test ${quiet} -eq 0
				then
					printf "Retaining %s as it differs from %s\n" "${entry}" "${btCopy}"
				fi
				continue
			fi
		fi
		case ${quiet} in
		0) # verbose
			echo Removing ${entry}
			rm -f ${entry}
			;;
		1) # quiet
			rm -f ${entry}
			;;
		2) # list remove only
			echo ${entry}
			;;
		3) # list retain only, be silent
			;;
		esac
	else
		case "${statusResult}" in
		svn*warning*)
			case ${quiet} in
			0)
				printf "Retaining %s as not in svn.\n" "${entry}"
				;;
			3) # list retained
				echo ${entry}
				;;
			esac
			;;
		A*)
			case ${quiet} in
			0)
				printf "Retaining %s due to addition not yet committed.\n" "${entry}"
				;;
			3) # list retained
				echo ${entry}
				;;
			esac
			;;
		M*)
			case ${quiet} in
			0)
				printf "Retaining %s due to local modifications.\n" "${entry}"
				;;
			3) # list retained
				echo ${entry}
				;;
			esac
			;;
		\?*)
			case ${quiet} in
			0)
				printf "Retaining %s as locally created file.\n" "${entry}"
				;;
			3) # list retained
				echo ${entry}
				;;
			esac
			;;
		esac
	fi
done
