#!/bin/sh
# Copyright (C) 2014 - 2018 FARGOS Development, LLC
# $Id$
# Do a workon on backing tree; makes use of sandbox_*.rc files generated
# by makeBTrc, usually invoked by checkoutNewBT

originDir=`dirname $0`
PATH="${PATH}:${originDir}"; export PATH
release="current"
targetArch=`${originDir}/buildArch`

btRoot=""

while test $# -gt 0
do
	case "${1}" in
	-h | -help | --help)
		printf "usage: %s [--btroot btRoot] [--ta targetArchitecture] [--bt] btName [[--command] command]\n" "${0}" >&2
		exit 1
		;;
	-ta | --ta)
		targetArch="${2}"
		shift
		;;
	-btroot | --btroot)
		btRoot="${2}"
		shift
		;;
	-bt | --bt)
		release="${2}"
		shift
		;;
	--command)
		shift	# consume it
		break	# stop consuming arguments
		;;
	*)
		release="${1}"
		shift
		break	# stop consuming arguments
		;;
	esac
	shift
done

if test $# -ne 0
then # there were command arguments
	cmdPrefix="--command "
fi
if test -z "${btRoot}"
then # btroot not specified as argument
	btRootDirs=`pathedit --space ${BT_ROOT_PATH:-/opt/backingTrees}`
	foundRoot=0
	for btRoot in ${btRootDirs}
	do
		if test -d "${btRoot}/${release}/obj"
		then
			foundRoot=1
			break
		fi
	done
else
	btRootDirs="${btRoot}"
fi

if test ! -d "${btRoot}/${release}/obj"
then
	printf "%s: backing tree %s does not exist under %s\n" "${0}" "${release}" "${btRootDirs}" >&2
	exit 1
fi

cd "${btRoot}/${release}/obj"
sbName=`pwd -P | awk -F/ '{ print $(NF-1) }'`

sbRC="sandbox_${targetArch}.rc"
if test ! -r "${sbRC}"
then
	printf "%s: cannot read sandbox rc %s under %s/%s\n" "${0}" "${sbRC}" "${btRoot}" "${release}" >&2
	exit 1
fi

exec workon -sb "${sbName}" -rc "${sbRC}" ${cmdPrefix} "$@"
