#! /bin/bash

platform="$1"
shift

if [ -z "${platform}" ]; then
	echo "Platforms:"
	echo "  native"
fi

for dir in work/libtclkit-*/ __fail__; do
	if [ "${platform}" = 'native' ]; then
		break
	fi

	if [ "${dir}" == '__fail__' ]; then
		if [ -z "${platform}" ]; then
			exit 0
		fi

		echo "No such platform: ${platform}" >&2

		exit 1
	fi

	dir="$(echo "${dir}" | sed 's@/$@@')"
	dir_platform_in="$(basename "${dir}-" | sed 's@^libtclkit-[^-]*-@@;s@-notk-@-@g;s@-xcompile-@-@g;s@-kitdll-@-@;s@-sdk-@-@g;s@-$@@')"
	case "${dir_platform_in}" in
		linux-i386|linux-amd64)
			dir_platforms=("${dir_platform_in}" "${dir_platform_in}-static")
			;;
		*)
			dir_platforms=("${dir_platform_in}")
			;;
	esac

	for dir_platform in "${dir_platforms[@]}"; do
		if [ -z "${platform}" ]; then
			echo "  $dir_platform"
		else
			if [ "${dir_platform}" = "${platform}" ]; then
				break 2
			fi
		fi
	done
done
dir="$(pwd)/${dir}"

case "${platform}" in
	native)
		platform=''
		;;
	linux-i386)
		platform="x86_64-redhat5-linux 32"
		;;
	linux-i386-static)
		platform="x86_64-unknown-linux-musl 32"
		;;
	linux-amd64)
		platform="x86_64-redhat5-linux 64"
		;;
	linux-amd64-static)
		platform="x86_64-unknown-linux-musl 64"
		;;
	linux-mipsel)
		platform="mipsel-unknown-linux-uclibc"
		;;
	solaris-amd64)
		platform="i386-pc-solaris2.10 64"
		;;
	solaris-i386)
		platform="i386-pc-solaris2.10"
		;;
	win32-i586)
		platform="i586-mingw32msvc"
		;;
	win64-amd64)
		platform="x86_64-w64-mingw32"
		;;
	android-arm)
		platform="arm-android9-linux-androideabi"
		;;
	netbsd-amd64)
		platform="x86_64-unknown-netbsd5"
		;;
	freebsd-amd64)
		platform="x86_64-unknown-freebsd8"
		;;
	'')
		exit 0
		;;
	*)
		echo "Unknown platform: ${platform}" >&2

		exit 1
		;;
esac

TCLKIT_SDK_DIR="${dir}"
export TCLKIT_SDK_DIR

make distclean

if [ "${platform}" != '' ]; then
	eval `~/root/cross-compilers/setup-cc $platform`

	platform="$(echo "${platform}" | cut -f1 -d ' ')"
fi

rm -rf INST
if [ "${platform}" = '' ]; then
	./configure --libdir="$(pwd)/INST" "$@" || exit 1
else
	./configure --host="${platform}" --libdir="$(pwd)/INST" --with-tcl="${dir}/lib" "$@" || exit 1
fi

make  || exit 1
make install

case "${platform}" in
	i586-mingw32msvc)
		make TCLSH="wine ${dir}/lib/tclsh.exe" test
		;;
	x86_64-w64-mingw32)
		WINEPREFIX="${HOME}/.wine64"
		export WINEPREFIX

		make TCLSH="wine64 ${dir}/lib/tclsh.exe" test
		;;
	x86_64-redhat5-linux)
		make TCLSH="LD_LIBRARY_PATH=${dir}/lib ${dir}/lib/tclsh" test
		;;
	'')
		make test
		;;
esac
