#! /bin/bash

TCLVERS="8.4.19"
if echo "$1" | grep '^[0-9][0-9]*\.' >/dev/null || echo "$1" | grep '^cvs_' >/dev/null; then
	TCLVERS="$1"

	shift
fi
export TCLVERS

mode="build"
if [ "$1" = "clean" ]; then
	shift

	mode="clean"
fi
if [ "$1" = "distclean" ]; then
	shift

	mode="distclean"
fi

CONFIGUREEXTRA="$@"
export CONFIGUREEXTRA

# Add packages implied by the additional arguments
if echo " ${CONFIGUREEXTRA} " | grep ' --enable-threads' >/dev/null 2>/dev/null; then
	ADDPKGS="${ADDPKGS} thread"
fi

failedpkgs=""
buildfailed="0"
for pkg in tcl tk itcl mk4tcl tclvfs zlib ${ADDPKGS} kitsh; do
	if [ "${mode}" = "distclean" ]; then
		rm -rf "${pkg}/src"
	fi

	if [ "${mode}" = "clean" -o "${mode}" = "distclean" ]; then
		rm -f "${pkg}/build.log"
		rm -rf "${pkg}/out" "${pkg}/inst" "${pkg}/build"

		continue
	fi

	echo -n "Building ${pkg} ..."

	failed="0"
	(
		cd "${pkg}" >/dev/null 2>/dev/null || exit 1

		./build.sh > build.log 2>&1 || exit 1
	) || failed="1"

	if [ "${failed}" = "1" ]; then
		echo " failed."
		failedpkgs="${failedpkgs} ${pkg}"
	else
		echo " done."
	fi

	case "${pkg}" in
		tcl)
			TCLCONFIGDIR=$(find "$(pwd)/tcl/build" -name tclConfig.sh | head -1 | sed 's@/[^/]*$@@')
			export TCLCONFIGDIR
			;;
	esac

	if [ "${failed}" = "1" ]; then
		buildfailed="1"
	fi
done

if [ "${mode}" = "clean" -o "${mode}" = "distclean" ]; then
	rm -f tclkit-*

	exit 0
fi

if [ -n "${failedpkgs}" ]; then
	echo "Failed to build:${failedpkgs}"
fi

if [ "${buildfailed}" != "0" ]; then
	echo 'WARNING: Build is likely incomplete or failed.' >&2
fi

cp 'kitsh/build'/kitsh-*/kit "tclkit-${TCLVERS}"

exit "${buildfailed}"
