#! /bin/bash

### XXX: Dietlibc is currently broken
exit 0

# URLs and versions
DIETLIBC_VERS='0.32'
DIETLIBC_URL="http://www.kernel.org/pub/linux/libs/dietlibc/dietlibc-${DIETLIBC_VERS}.tar.bz2"
DIETLIBC_TARBALL="src/dietlibc-${DIETLIBC_VERS}.tar.bz2"
DIETLIBC_DIR="dietlibc-${DIETLIBC_VERS}"

# Main script
CCNAME="$1"
CCDIR="$2"
PREFIX="${CCDIR}/dietlibc"
STAGE="$4"

# Clean
if [ "$1" = "distclean" ]; then
	rm -f "${DIETLIBC_TARBALL}"

	set -- clean
fi

if [ "$1" = "clean" ]; then
	rm -rf "${DIETLIBC_DIR}"

	exit 0
fi

# Only build uclibc for linux-uclibc platforms
if ! echo "${CCNAME}" | egrep -- '^(arm.*|hppa1.*|ia64|i[3-9]86|mips.*|s390|sparc.*|ppc.*|x86_64)-.*-linux' >/dev/null; then
	exit 0
fi

# Skip building if we are already installed
if [ -f "${PREFIX}/bin/diet" ]; then
	exit 0
fi

# Only build the first time around
if [ "${STAGE}" != "stage1" ]; then
	exit 0
fi

# Inform the user of what we are doing
echo ' * Building diet C library (dietlibc)'

# Download source
. 'scripts/common'

download "${DIETLIBC_URL}" "${DIETLIBC_TARBALL}" || exit 1

rm -rf "${DIETLIBC_DIR}"
bzip2 -dc "${DIETLIBC_TARBALL}" | tar -xf -

# Patch up source as needed
case "${CCNAME}" in
	armel-*)
		sed 's@-mabi=aapcs-linux.*@@' "${DIETLIBC_DIR}/arm/Makefile.add" > "${DIETLIBC_DIR}/arm/Makefile.add.new"
		cat "${DIETLIBC_DIR}/arm/Makefile.add.new" > "${DIETLIBC_DIR}/arm/Makefile.add"
		rm -f "${DIETLIBC_DIR}/arm/Makefile.add.new"
                ;;
esac

(
	cd "${DIETLIBC_DIR}" || exit 1

	# Create an alias for the compiler OS field if needed
	ccosname="$(echo "${CCNAME}" | cut -f 1 -d '-')"
	if [ "${ccosname}" != "${arch}" ]; then
		ln -s "bin-${arch}" "bin-${ccosname}"
	fi

	# Build a local copy of diet libc first, since the cross-compile build references it
	${MAKE} prefix="${PREFIX}" || exit 1

	# Install local copy to get native executables
	${MAKE} prefix="${PREFIX}" install || exit 1

	# Build
	${MAKE} CROSS="${CCNAME}-" prefix="${PREFIX}" ARCH="${arch}" ${extra_make_options} || exit 1

	# Install
	${MAKE} CROSS="${CCNAME}-" prefix="${PREFIX}" ARCH="${arch}" ${extra_make_options} install || exit 1

	if [ "${ccosname}" != "${arch}" ]; then
		ln -s "lib-${arch}" "${PREFIX}/lib-${ccosname}"
	fi
) || exit 1

rm -rf "${DIETLIBC_DIR}"

exit 0
