#!/bin/sh

# Build the T3 porting kit test files.
# Note: run from same dir as this file is in.

TADS3_DIR=${XTADS_TADS_DEV_ROOT}/tads3
GAMES_SRC_DIR="$TADS3_DIR"/test/data
TEMP_FILES_DIR=tempfiles
GAMES_DIR=games
BUILT_GAMES_LOGFILE=built.log

#
# NB! This script only manages to build a subset of the regression tests.
# Various forms of per-test jiggling (both here and in template.t3m) are needed for the rest.
#

if [ ! -d "$GAMES_DIR" ]; then
	mkdir "$GAMES_DIR"
fi
if [ ! -d "$TEMP_FILES_DIR" ]; then
	mkdir "$TEMP_FILES_DIR"
fi
if [ -f "$BUILT_GAMES_LOGFILE" ]; then
	rm "$BUILT_GAMES_LOGFILE"
fi

#for file in "$GAMES_SRC_DIR"/*.t
for file in "$GAMES_SRC_DIR"/timeout.t
do
	rm $TEMP_FILES_DIR/*.*

	echo "-----------------------------------"
	echo "Consider $file ..."
	GAME_FILE_BASENAME=`basename $file .t`
	
	grep -q 'main(' "$file"
	FOUND_MAIN=$?
	if [ $FOUND_MAIN -eq 0 ]; then
	
		echo "Build $GAME_FILE_BASENAME ..."
		echo "$GAME_FILE_BASENAME" >>"$BUILT_GAMES_LOGFILE"
		T3M_FILE_FQ_NAME="$TEMP_FILES_DIR"/"$GAME_FILE_BASENAME".t3m
		#TODO if src file contains _main, add ... options
		EXTRA_OPTIONS=
		grep -q _main "$file"
		FOUND=$?
		if [ $FOUND -eq 0 ]; then
			echo 'has _main'
			EXTRA_OPTIONS="$EXTRA_OPTIONS -nodef -nopre"
				# prevents tads3/lib/_main.t from being included
		fi
		grep -q 'main()' "$file"
		FOUND_MAIN_NOARGS=$?
		if [ $FOUND_MAIN_NOARGS -eq 0 ]; then
			echo 'has main()'
			#TODO temp rm'd for date/timezone: 
			#EXTRA_OPTIONS="$EXTRA_OPTIONS -nodef -nopre"
		fi
		sed -e "s|\${tempFilesDir}|../$TEMP_FILES_DIR|g" -e "s|\${gamesDir}|../$GAMES_DIR|g" -e "s/\${gameName}/$GAME_FILE_BASENAME/g" -e "s|\${tads3Dir}|../$TADS3_DIR|g" -e "s|\${extraOptions}|$EXTRA_OPTIONS|g"  template.t3m >"$T3M_FILE_FQ_NAME"
		t3make -f "$T3M_FILE_FQ_NAME"
	
	fi # [ $FOUND_MAIN -eq 0 ]
done
