#! /bin/bash

if [ ! -x "./platform" ]; then
	echo 'ERROR: Platform script not found: ./platform' >&2

	exit 1
fi

CLEANONLY=0
DISTCLEAN=0
if [ "$1" = "clean" ]; then
	shift
	CLEANONLY=1
fi
if [ "$1" = "distclean" ]; then
	shift
	CLEANONLY=1
	DISTCLEAN=1
fi
export CLEANONLY DISTCLEAN

CONFIGUREEXTRA="$@"
export CONFIGUREEXTRA

# Determine path to "tclConfig.sh"
rm -rf tcl/build tcl/inst
rm -f platform.magic.*
if [ "${DISTCLEAN}" = "1" ]; then
	rm -rf tcl
fi

if [ "${CLEANONLY}" = "0" ]; then
	TCLVERS="8.4.19"
	TCLPRIVATE="$(pwd)/tcl/build/tcl${TCLVERS}"
	PROJROOTDIR="$(pwd)"
	TCLINSTDIR="$(pwd)/tcl/inst"
	export TCLVERS TCLPRIVATE PROJROOTDIR TCLINSTDIR

	mkdir tcl tcl/build >/dev/null 2>/dev/null

	if [ ! -f "tcl/src/tcl${TCLVERS}.tar.gz" ]; then
		mkdir tcl/src >/dev/null 2>/dev/null
		wget -o /dev/null -O "tcl/src/tcl${TCLVERS}.tar.gz" "http://prdownloads.sourceforge.net/tcl/tcl${TCLVERS}-src.tar.gz"
	fi

	echo "Building Tcl ${TCLVERS}"
	(
		mkdir tcl/build >/dev/null 2>/dev/null
		cd tcl/build || exit 1
		gzip -dc "../src/tcl${TCLVERS}.tar.gz" | tar -xf -

		for dir in unix win macosx; do
			cd "${TCLPRIVATE}/${dir}" || exit 1

			echo " Executing: ./configure ${CONFIGUREEXTRA}"
			./configure --disable-threads ${CONFIGUREEXTRA} --prefix="${TCLINSTDIR}"

			${MAKE:-make} || continue
			${MAKE:-make} install || break

			LD_LIBRARY_PATH=".:${LD_LIBRARY_PATH}"
			LD_RUN_PATH=".:${LD_RUN_PATH}"
			export LD_LIBRARY_PATH LD_RUN_PATH

			file tclsh tclsh*.exe 2>/dev/null | grep -iv 'No such file' > "${PROJROOTDIR}/platform.magic.file"
			if [ -f tclsh*.exe ]; then
				echo 'puts "$::tcl_platform(os)"' | ./tclsh*.exe > "${PROJROOTDIR}/platform.magic.os" 2>/dev/null
			else
				echo 'puts "$::tcl_platform(os)"' | ./tclsh > "${PROJROOTDIR}/platform.magic.os" 2>/dev/null
			fi
			echo "${dir}" > "${PROJROOTDIR}/platform.magic.platform"
			pwd > "${PROJROOTDIR}/platform.magic.dir"

			break
		done
	) > "tcl/build/build.log" 2>&1 || (
		echo 'Failed to build Tcl.  See "./tcl/build/build.log"'
		echo 'Proceeding with system Tcl.  Building might fail.'
	)

	TCLBUILDDIR="$(cat "${PROJROOTDIR}/platform.magic.dir")"
	export TCLBUILDDIR

	if [ -d "${TCLINSTDIR}" -a -f "${TCLINSTDIR}/lib/tclConfig.sh" ]; then
		TCLCONFIGDIR="${TCLINSTDIR}/lib"
	elif [ -d "${TCLBUILDDIR}" -a -f "${TCLBUILDDIR}/tclConfig.sh" ]; then
		TCLCONFIGDIR="${TCLBUILDDIR}"
	else
		unset TCLPRIVATE

		TCLCONFIGDIR=$(
			(
				echo "${LD_LIBRARY_PATH}" | tr ':' "\n"
				cat /etc/ld.so.conf 2>/dev/null
				crle 2>/dev/null | grep '^ *Default Library Path' | sed 's@^ *Default Library Path[^:]*:[^:]*/@/@' | tr ':' "\n"
			) | grep '^/' | while read chklibdir; do
				if [ -f "${chklibdir}/tclConfig.sh" ]; then
					echo "${chklibdir}"
					break
				fi
			done
		)
		if [ -z "${TCLCONFIGDIR}" ]; then
			TCLCONFIGDIR="/usr/lib"
		fi

		TCLPRIVATE="$(dirname "${TCLCONFIGDIR}")/include/tcl-private"
	fi

	ADDFLAGS=""
	if [ -n "${TCLPRIVATE}" ]; then
		ADDFLAGS="${ADDFLAGS} -I${TCLPRIVATE} -I${TCLPRIVATE}/generic"
	fi
	if [ -n "${TCLBUILDDIR}" ]; then
		ADDFLAGS="${ADDFLAGS} -I${TCLBUILDDIR}"
	fi
	CFLAGS="${ADDFLAGS} ${CFLAGS}"
	CPPFLAGS="${ADDFLAGS} ${CPPFLAGS}"

	unset TCLVERS
	unset ADDFLAGS
	export TCLBUILDDIR TCLCONFIGDIR TCLPRIVATE CFLAGS CPPFLAGS
fi

# Determine platform
if [ -z "${FORCE_PLATFORM}" ]; then
	PLATFORM="$(./platform)"
	export PLATFORM
else
	PLATFORM="${FORCE_PLATFORM}"
fi

# Build all appropriate directories
faileddirs=""
for dir in */; do
	export dir

	if [ ! -f "${dir}/build.sh" ]; then
		continue
	fi

	if [ "${CLEANONLY}" = "0" ]; then
		echo "Building ${dir}"
	fi

	failed=0
	(
		cd "${dir}" || exit 1

		rm -rf "build" "out"
		rm -f failed-*.log
		if [ "${DISTCLEAN}" = "1" ]; then
			rm -rf "src"
		fi
		if [ "${CLEANONLY}" = "1" ]; then
			exit 0
		fi

		mkdir -p "out/${PLATFORM}" >/dev/null 2>/dev/null

		./build.sh > "out/${PLATFORM}/build.log" 2>&1 || exit 1
	) || failed=1

	if [ "${failed}" = "1" ]; then
		cp "${dir}/out/${PLATFORM}/build.log" "${dir}/failed-${PLATFORM}-`hostname`.log"

		rm -rf "${dir}/out"
		faileddirs="${faileddirs} ${dir}"
		echo "Failed to build ${dir}"
	fi
done

# Cleanup is done at this point
if [ "${CLEANONLY}" = "1" ]; then
	exit 0
fi

# Let the user know what failed to build
if [ -n "${faileddirs}" ]; then
	echo "The following failed to build:${faileddirs}"
fi

# Create tarfile of built packages
DATECODE="$(date +%Y%m%d%H%M)"
OUTFILEBASE="tclpkgs-${PLATFORM}-${DATECODE}"
tar -cf - */out | bzip2 -9c > "${OUTFILEBASE}.tar.bz2"

exit 0
