#!/bin/sh
# Copyright (C) 2010 - 2018 FARGOS Development, LLC
# $Id$
# rmsb - remove sandbox
# rmsb [-i] [--force] --sb sandboxName [--rc rcFile]
#
progName=`basename $0`
originDir=`dirname $0`
rcFile="${HOME}/.sandboxrc"
interactive=0
force=0
sbName="${SB_NAME}"	# use current sandbox as default
while test $# -gt 0
do
	case "${1}" in
	-h | -help | --help)
		printf "usage: %s [--force] [-i] [--rc rcFile] --sb sandboxName\n" "$0" >&2
		printf "  --force = remove all files under sandbox tree\n" >&2
		printf "  -i = interactive mode\n" >&2
		printf "  --rc = specify alternate rc file, default is %s\n" "${rcFile}" >&2
		exit 1
		;;
	-i)
		interactive=1
		;;
	-sb | --sb)
		sbName="${2}"
		shift
		;;
	-force | --force)
		force=1
		;;
	-rc | --rc)
		rcFile="${2}"
		shift
		;;
	-*)
		printf "%s: unrecognized option \"%s\"\n" "${0}" "${1}" >&2
		exit 1
		;;
	*)
		printf "%s: unrecognized argument \"%s\"\n" "${0}" "${1}" >&2
		exit 1
		;;
	esac
	shift
done

if test -z "${sbName}"
then
	printf "%s: sandbox name was not specified.\n" "$0" >&2
	if test ${interactive} -eq 0
	then
		exit 1
	fi
	printf "  Enter name of sandbox: "
	read sbName
	if test -z "${sbName}"
	then
		printf "%s: sandbox name was not specified.\n" "$0" >&2
		exit 1
	fi
fi
tmpFile=`dirname "${rcFile}"`/newsbrcfile.txt

# remove sandbox
if test ${interactive} -eq 1
then
	printf "Are you sure you want to remove the %s sandbox? " ${sbName}
	read answer
	if test "${answer}" != "y"
	then
		print "%s: aborted\n" "$0" >&2
		exit 1
	fi
fi
# get sandbox root
sbDir=`${originDir}/getsbattr -null -sb ${sbName} sbroot`
if test -z "${sbDir}"
then
	printf "rmsb:  cannot remove sandbox %s as tree is not defined.\n" ${sbName} >&2
	exit 1
fi
sed -e "/SB_${sbName}_/d" ${rcFile} > ${tmpFile}
mv ${tmpFile} ${rcFile}
# don't remove tree unless force specified
if test ${force} -eq 1
then
	# see if any other sandbox references it
	otherRefs=`fgrep -c ${sbDir} "${rcFile}"`
	if test "${otherRefs}" -ne 0
	then
		printf "rmsb:  cannot remove %s tree  as there are %d additional references\n" "${sbDir}" "${otherRefs}" >&2
		exit 1
	fi
	printf "Removing %s tree\n" "${sbDir}"
	resolvedDir=`eval echo ${sbDir}`
	rm -rf "${resolvedDir}"
else
	printf "Left %s tree in place\n" "${sbDir}"
fi
exit 0
