#!/bin/sh
# Generate RC file for a backing tree, store under ${btRoot}/${bldName}/obj.
# Copyright (C) 2014 - 2018 FARGOS Development, LLC
# $Id$

# default is first element of BT_ROOT_PATH
firstBTrootDir=`pathedit --space ${BT_ROOT_PATH:-/opt/backingTrees} | awk '{ print $1; }'`
btRoot="${firstBTrootDir}"
SB_BUILD_ARCH=`buildArch`
targetArch=`buildArch`
doForce=0
bldName="current"

while test $# -gt 0
do
	case "${1}" in
	-h | -help | --help)
		printf "usage: %s [--force] [--btroot btRoot] [--bt backingTree] --ta targetArchitecture\n" "${0}" >&2
		printf "  --btroot = specify alternate backing tree root, default is \"%s\"\n" "${btRoot}" >&2
		printf "  --bt = specify backing tree, defaults to \"%s\"\n" "${bldName}" >&2
		printf "  --ta = target architecture, default is native;\n" >&2
		printf "  --force = allow existing rc file to be overwritten\n" >&2
		exit 1
		;;
	-bt | --bt)
		bldName="${2}"
		shift
		;;
	-btroot | --btroot)
		btRoot="${2}"
		shift
		;;
	-ta | --ta)
		targetArch="${2}"
		shift
		;;
	-force | --force)
		doForce=1
		;;
	*)
		printf "%s: unrecognized argument: \"%s\"\n" "${0}" "${1}" >&2
		exit 1
		;;
	esac
	shift
done

if test -z "${bldName}"
then
	printf "%s: no backing tree name specified\n" "${0}" >&2
	exit 1
fi

SB_TARGET_ARCH="${targetArch}"

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

cd "${btRoot}/${bldName}/obj"
actualBldName=`pwd -P | awk -F/ '{ print $(NF-1) }'`
if test "${bldName}" != "${actualBldName}"
then
	printf "%s: using \"%s\" as name for \"%s\"\n" "${0}" "${actualBldName}" "${bldName}"
	bldName="${actualBldName}"
fi

# create sandbox rc file for backing tree
tempSB="${btRoot}/${bldName}/obj/sandbox_${SB_TARGET_ARCH}.rc"
if test -r "${tempSB}"
then
	if test ${doForce} -eq 0
	then
		printf "%s: sandbox rc file already exists: %s\n" "${0}" "${tempSB}" >&2
		exit 1
	fi
	printf "%s: overwriting existing sandbox rc file \"%s\"\n" "${0}" "${tempSB}"
fi

if test "${btRoot}" = "${firstBTrootDir}" -a -n "${BT_ROOT_DIR}"
then # use environment variable name rather than actual path
	useBTdir='${BT_ROOT_DIR}'
else
	useBTdir="${btRoot}"
fi

cat > ${tempSB} <<endText
SB_${bldName}_btpath_ ${useBTdir}/${bldName}
SB_${bldName}_sbname_ ${bldName}
SB_${bldName}_sbroot_ ${useBTdir}/${bldName}
SB_${bldName}_defaultTargetArch_ ${SB_TARGET_ARCH}
SB_${bldName}_description_ Backing tree ${bldName}
endText
exit 0
