#! /usr/bin/env bash
#
#	Version of _solo script designed to be embedded in the GemStone product tree.
# Expect extent0.rowan.dbf (solo extent) to be found in $GEMSTONE/bin
#
#	Expected script command line:
#		script [ <script-args> ] [ -- <topaz-command-line-args> ]
#

set -e

scriptFile=$1
shift

topazArgs=()
scriptArgs=()
for arg in "$@"; do
		if [[ "$endOfScriptArgs"x = "x" ]] && [[ "$arg" = "--" ]] ; then
			endOfScriptArgs="true"
		else
			if [ "$endOfScriptArgs"x = "x" ] ; then
				scriptArgs+=("$arg")
			else
				topazArgs+=("$arg")
			fi
		fi
		shift
done

if [ "$GEMSTONE"x = "x" ] ; then
	echo "Environment variable GEMSTONE must be defined"
	exit 1
fi
GEM_SOLO_EXTENT="$GEMSTONE/bin/extent0.rowan.dbf"

skip="skip"
if [ "$skip"x = "x" ] ; then
	echo "======================"
	echo "script file: $scriptFile"
	echo "script args: ${scriptArgs[@]}"
	echo "topaz args: ${topazArgs[@]}"
	echo "======================"
	# exit 0
fi

export SUPERDOIT_GEMSTONE_VERSION=`awk 'NR==2{print $1; exit}' $GEMSTONE/version.txt`

case $SUPERDOIT_GEMSTONE_VERSION in
	3.6.[4-9]) 
		export SUPERDOIT_DIR="$GEMSTONE/upgrade/projects/superDoit"
		;;
	3.7.*)
		export SUPERDOIT_DIR="$GEMSTONE/projects/superDoit"
		;;
	*)
		if [ "$SUPERDOIT_DIR"x = "x" ] ; then
			echo "Expected SUPERDOIT env var to be defined"
			exit 1
		fi
		;;
esac
export gemstoneDir="$SUPERDOIT_DIR/gemstone"

$GEMSTONE/bin/topaz -l \
	-I "$gemstoneDir/topazini_solo" \
	-C "GEM_SOLO_EXTENT=$GEM_SOLO_EXTENT" \
	-q \
	${topazArgs[@]} \
	-S $gemstoneDir/productTree/superdoit.tpz -- $scriptFile -- ${scriptArgs[@]}
