#! /bin/bash

CCROOT="$(dirname "$(which "$0")")"

idx=0
for platform in "${CCROOT}"/*; do
	if [ ! -d "${platform}" ]; then
		continue
	fi

        platform="$(basename "${platform}")"

	if [ ! -d "${CCROOT}/${platform}/${platform}" ]; then
		continue
	fi

        platforms[${idx}]="${platform}"
        idx=$[${idx} + 1]
done

if [ -z "$1" ]; then
	echo "Available platforms:"

	for platform in "${platforms[@]}"; do
		echo "  ${platform}"
	done

	exit 0
fi

CCNAME="$1"
shift

# Canonicalize symbolic links
if [ -L "${CCROOT}/${CCNAME}" ]; then
	CCNAME="$(readlink "${CCROOT}/${CCNAME}" | sed 's@^.*/@@')"
fi

found='0'
for platform in "${platforms[@]}"; do
	if [ "${platform}" = "${CCNAME}" ]; then
		found='1'
		break
	fi
done

if [ "${found}" != '1' ]; then
	echo "Unknown platform: ${CCNAME}" >&2

	exit 1
fi

case "${CCNAME}" in
	x86_64-*|hppa64-*)
		have_64bit='1'
		;;
	*)
		have_64bit='0'
		;;
esac

if [ -n "$1" ]; then
	if [ "$1" = "64" ]; then
		want_64bit='1'
	else
		want_64bit='0'
	fi
else
	want_64bit="${have_64bit}"
fi

if [ "${have_64bit}" != "${want_64bit}" ]; then
	if [ "${want_64bit}" = "1" ]; then
		CC_ADD=' -m64'
	else
		CC_ADD=' -m32'
	fi
fi

if [ -z "${CC_FOR_BUILD}" -a -z "${HOST_CC}" ]; then
	if [ -n "${CC}" ]; then
		CC_FOR_BUILD="${CC}"
	else
		tmpfile="${TMPDIR:-/tmp}/setup-cc-find-cc-$$${RANDOM}${RANDOM}${RANDOM}"
		rm -f "${tmpfile}.o" "${tmpfile}"

		for try_cc in cc gcc c89 c99; do
			try_cc="$(which "${try_cc}" 2>/dev/null)"

			if [ ! -f "${try_cc}" ]; then
				continue
			fi

			touch "${tmpfile}"
			"${try_cc}" -o "${tmpfile}.o" -c "${tmpfile}" 2>/dev/null >/dev/null || continue

			CC_FOR_BUILD="${try_cc}"

			break
		done

		rm -f "${tmpfile}.o" "${tmpfile}"
	fi
elif [ -z "${CC_FOR_BUILD}" -a -n "${HOST_CC}" ]; then
	CC_FOR_BUILD="${HOST_CC}"
fi

CCROOT="$(cd "${CCROOT}" && pwd)"
echo "PATH='${PATH}:${CCROOT}/${CCNAME}/bin';"
echo "AR='${CCNAME}-ar';"
echo "AS='${CCNAME}-as';"
echo "CC='${CCNAME}-gcc${CC_ADD}';"
echo "CXX='${CCNAME}-g++${CC_ADD}';"
echo "LD='${CCNAME}-ld';"
echo "NM='${CCNAME}-nm';"
echo "RANLIB='${CCNAME}-ranlib';"
echo "STRIP='${CCNAME}-strip';"
echo "PKG_CONFIG='${CCNAME}-pkg-config';"
echo "PKGCONFIG='${CCNAME}-pkg-config';"
echo "CC_FOR_BUILD='${CC_FOR_BUILD}';"
echo "HOST_CC='${CC_FOR_BUILD}';"
echo "PKG_CONFIG_DIR='';"
echo "PKG_CONFIG_LIBDIR='${CCROOT}/${CCNAME}/${CCNAME}/lib/pkgconfig';"
echo 'export PATH AR AS CC CXX LD NM RANLIB STRIP PKG_CONFIG PKGCONFIG CC_FOR_BUILD HOST_CC PKG_CONFIG_DIR PKG_CONFIG_LIBDIR;'
