#!/bin/bash
#
# This script builds the m68k-uclinux- or arm-elf- toolchain for use
# with uClinux.  It can be used to build for almost any architecture
# without too much change.
#
# Before running you will need to obtain the following files
# (if you don't have them in this directory)
#
# For the GCC 2.95 toolchain:
#    gcc-2.95.3.tar.bz2            in current directory (or a gzipped version)
#    gcc-2.95.3-full.patch         in current directory
#    gcc-2.95.3-arm-pic.patch      in current directory
#    gcc-2.95.3-arm-pic.patch2     in current directory
#    gcc-2.95.3-arm-mlib.patch     in current directory
#    gcc-2.95.3-sigset.patch       in current directory
#    gcc-2.95.3-m68k-zext.patch    in current directory
#    STLport-4.5.3.tar.gz          in current directory
#    STLport-4.5.3.patch           in current directory
#
# For the GCC 3.3.2 toolchain:
#    gcc-3.3.2-coldfire-frame.patch
#    gcc-3.3.2-coldfire-omitfrmptr.patch
#    gcc-3.3.2-coldfire-targets.patch
#    gcc-3.3.2-uclinux-thunk.patch
#    gcc-3.3.2-uclinux-idshlib.patch
#    gcc-3.3.2-uclinux-specs.patch
#    gcc-core-3.3.2.tar.bz2
#    gcc-g++-3.3.2.tar.bz2
#    uClibc-gcc332fix.patch
#
# For the GCC 3.4.0 toolchain:
#    gcc-3.4.0.tar.bz2
#    gcc-3.4.0-arm-multilib.patch
#    gcc-3.4.0-arm-deflibspec.patch
#
# For GDB 6.1:
#    gdb-6.1.tar.bz2
#
# For GDB 6.0:
#    gdb-6.0.tar.bz2
#
# For GDB 5.3:
#    gdb-5.3.tar.bz2
#
# Common files:
#    binutils-2.14.90.0.7.tar.bz2 (or binutils-2.15.90.0.3.tar.bz2)
#    elf2flt-20040326.tar.bz2
#    genromfs-0.5.1.tar.gz
#    m68k-bdm-1.3.0.tar.bz2
#    uClibc-0.9.26.tar.bz2
#    uClibc-0.9.26-m68k.config
#    uClibc-0.9.26-exec_alloc.patch
#
# You will also need:
#    - a current uClinux kernel (2.0/2.4/2.6) from cvs.uclinux.org
#    - to change the EDIT section below appropriately
#
# Unless you modify PREFIX below, you will need to be root to run this
# script correctly.
#
# To build everything run "./build-uclinux-tools.sh build 2>&1 | tee errs"
#
# WARNING: it removes all current tools from $PREFIX, so back them up first :-)
#
# Copyright (C) 2001-2003 David McCullough <davidm@snapgear.com>
#
# Cygwin changes from Heiko Degenhardt <linux@sentec-elektronik.de>
#     I've modified that script to build the toolchain under Cygwin.
#     My changes are based on the information I found at
#     http://fiddes.net/coldfire/ # (thanks to David J. Fiddes) and the
#     very good introduction at
#     http://www.uclinux.org/pub/uClinux/archive/8306.html (thanks to
#     Paul M. Banasik (PaulMBanasik@eaton.com).
#
# Support for GCC 3.x and binutils 2.14.x by Bernardo Innocenti <bernie@codewiz.org>,
#     based on Peter Barada's Coldfire patches for gcc-3.2.3 and binutils-2.13.
#
# Support added for GCC 3.4.0 (arm-elf only) and binutils 2.15.x by Steve
# Miller <steve.miller@st.com>
#
# GDB/Insight integration by Bernardo Innocenti <bernie@codewiz.org>,
#     includes Chris John's BDM patches for GDB.
#

BASEDIR="`pwd`"

#############################################################
#
# EDIT these to suit your system and source locations
#

TARGET=m68k-elf
#TARGET=arm-elf

# set your install directory here and add the correct PATH
#PREFIX=/usr/local/m68k-uclinux-tools

BINUTILSVERS="2.14.90.0.8"
#BINUTILSVERS="2.15.91.0.1"  *** ld segfaults ***

#GCCVERS="2.95.3"
#GCCVERS="3.3.3"
GCCVERS="3.4.0"
#GCCVERS="3.5-20040530"

#GDBVERS="5.3"
#GDBVERS="6.0"
GDBVERS="6.1"

# Only needed by the m68k toolchain
BDMVERS="1.3.0"

UCLIBCVERS="0.9.26"

ELF2FLTVERS="20040326"

# set $ROOTDIR to the root directory of your uClinux source tree.
# Needed to build uClibc with -mid-shared-library support.
#
ROOTDIR="${BASEDIR}/uclinux"

#
# Either 2.4.x or 2.6.x are supported by uClibc-0.9.26+
#
#KERNEL="${ROOTDIR}/linux-2.4.x"
KERNEL="${ROOTDIR}/linux-2.6.x"

#
# Override this host's CFLAGS to build the tools for older hosts
#
CFLAGS=-O2
CXXFLAGS=-O2
CPPFLAGS=

MAKE=make
PATCH=patch
ELF2FLT="$BASEDIR/elf2flt-${ELF2FLTVERS}"
BINUTILS="${BASEDIR}/binutils-${BINUTILSVERS}"
GCC="${BASEDIR}/gcc-${GCCVERS}"
GDB="${BASEDIR}/gdb-${GDBVERS}"
BDM="${BASEDIR}/m68k-bdm-${BDMVERS}"
UCLIBC="${BASEDIR}/uClibc-${UCLIBCVERS}"

#############################################################
#
# Don't edit these
#

sysinclude=include

#############################################################
#
# mark stage done
#
mark()
{
	echo "STAGE $1 - complete"
	touch "$BASEDIR/STAGE$1"
}

#
# check if stage should be built
#
schk()
{
	echo "--------------------------------------------------------"
	[ -f "$BASEDIR/STAGE$1" ] && echo "STAGE $1 - already built" && return 1
	echo "STAGE $1 - needs building"
	return 0
}

#
# extract most archive format files
#
extract()
{
	for i in "$@"; do
		echo "Extracting $i..."
		case "$i" in
		*.tar.gz|*.tgz)   tar xzf "$i" ;;
		*.tar.bz2|*.tbz2) bunzip2 < "$i" | tar xf - ;;
		*.tar)            tar xf  "$i" ;;
		*)
			echo "Unknown file format $i" >&2
			return 1
			;;
		esac
	done
	return 0
}

#
# Apply a patch
#
apply_patch()
{
	echo "Applying patch $1..."

	[ "x$2" = "x" ] || cd $2 || exit 1
	${PATCH} -p1 -E < "${BASEDIR}/$1" || exit 1
	[ "x$2" = "x" ] || cd ${BASEDIR}
}

#
# work like cp -L -r on systems without it
#
cp_Lr()
{
	cd "$1/."
	[ -d "$2" ] || mkdir -p $2
	find . | cpio -pLvdum "$2/."
}

#############################################################
#
# cleanup
#

clean_sources()
{
	echo "Removing source and build dirs..."
	rm -rf ${BINUTILS}
	rm -rf ${GCC}
	rm -rf ${GDB}
	rm -rf ${TARGET}-binutils
	rm -rf ${TARGET}-gcc
	rm -rf ${TARGET}-gdb
	rm -rf ${BDM}-build
	rm -rf ${BDM}
	rm -rf ${UCLIBC}
	rm -rf ${ELF2FLT}
	rm -rf ${TARGET}-elf2flt
	rm -rf genromfs-0.5.1
	rm -rf STLport-4.5.3
}

clean_uninstall()
{
	echo "Removing installed binaries..."
	rm -rf ${PREFIX}/${TARGET}
	rm -rf ${PREFIX}/${OLDTARGET}
	if [ "${GDBPREFIX}" != "${PREFIX}" ] ; then
		rm -rf ${GDBPREFIX}
	fi
	rm -rf ${GCCLIB}
	if [ ! -z "${GCCLIBEXEC}" ]
	then
		rm -rf ${GCCLIBEXEC}
	fi
	rm -rf ${GLIBCXXHEADERS}
	rm -rf ${PREFIX}/bin/${TARGET}*
	rm -rf ${PREFIX}/bin/${OLDTARGET}*
	rm -rf ${PREFIX}/bin/${GDBTARGET}*
	rm -rf ${PREFIX}/bin/genromfs${EXE}
	rm -rf ${PREFIX}/man/*/${TARGET}-*
}

clean_all()
{
	echo "Removing stage completition flags..."
	rm -f ${BASEDIR}/STAGE*
	clean_sources
}


#############################################################
#
# Setup GCC version-specific paths
#
gcc_version_setup()
{
	if [ -f "${GCC}/gcc/version.c" ] ; then
		#
		# Don't let us get easily fooled by awkward package naming schemes:
		# extract GCC version from sources the same way top-level configure does
		#
		gcc_version_full=`grep version_string "${GCC}/gcc/version.c" | sed -e 's/.*"\([^"]*\)".*/\1/'`
		gcc_version=`echo ${gcc_version_full} | sed -e 's/\([^ ]*\) .*/\1/'`
	else
		#
		# We have not yet extracted the tarballs: try to guess the
		# installation version from the package version
		#
		gcc_version=${GCCVERS%%-*}
	fi

	#
	# Handle GCC installation directories
	#
	OLDTARGET="$TARGET"

	case "${GCCVERS}" in
	2.95*)
		GCCLIB=${PREFIX}/lib/gcc-lib/${TARGET}/${gcc_version}
		GLIBCXXHEADERS=${GCCLIB}/include
		;;
	3.3*)
		GCCLIB=${PREFIX}/lib/gcc-lib/${TARGET}/${gcc_version}
		GLIBCXXHEADERS=${PREFIX}/include/c++/${gcc_version}
		;;
	3.[45]*)
		case "${TARGET}" in
		m68k-*)
			#
			# Handle the target switch mess
			#
			TARGET="m68k-uclinux"
			OLDTARGET="m68k-elf"
			;;
		esac
		GCCLIB=${PREFIX}/lib/gcc/${TARGET}/${gcc_version}
		GCCLIBEXEC=${PREFIX}/libexec/gcc/${TARGET}/${gcc_version}
		GLIBCXXHEADERS=${PREFIX}/include/c++/${gcc_version}
		;;
	*)
		echo >&2 "Unsupported GCC version ${GCCVERS} (${gcc_version})"
		exit 1
		;;
	esac
}




#############################################################
#
# Clean any previous runs, extract everything and apply all patches
#

stage1()
{
	schk 1 || return 0

	# clean any previous runs
	clean_sources

	#
	# extract everything
	#
	extract binutils-${BINUTILSVERS}.tar*
	extract elf2flt-${ELF2FLTVERS}.tar*
	extract uClibc-${UCLIBCVERS}.tar*
	extract gcc-*${GCCVERS}.tar*
	extract gdb-${GDBVERS}.tar*

	#
	# Apply all patches
	#

	case "${BINUTILSVERS}" in
	2.14.*)
		apply_patch binutils-uclinux_target.patch "${BINUTILS}"
	esac

	case "${UCLIBCVERS}" in
	0.9.25 | 0.9.26)
		apply_patch uClibc-0.9.26-exec_alloc.patch "$UCLIBC"
		apply_patch uClibc-0.9.26-ptrace-lvalue.patch "$UCLIBC"
		apply_patch uClibc-0.9.26-syscalls-inline.patch "$UCLIBC"
		;;
	esac
	apply_patch uClibc-arm.patch "$UCLIBC"

	case "${GCCVERS}" in
	2.95.3)
		rm -rf "${GCC}/libio"
		rm -rf "${GCC}/libstdc++"
		apply_patch gcc-2.95.3-full.patch "$GCC"
		apply_patch gcc-2.95.3-arm-pic.patch "$GCC"
		apply_patch gcc-2.95.3-arm-pic.patch2 "$GCC"
		apply_patch gcc-2.95.3-arm-mlib.patch "$GCC"
		apply_patch gcc-2.95.3-sigset.patch "$GCC"
		apply_patch gcc-2.95.3-m68k-zext.patch "$GCC"
		if [ "${CYGWIN}" ]; then
			apply_patch gcc-2.95.3-cygwin-020611.patch "$GCC"
		fi
		extract STLport-4.5.3.tar.gz
		apply_patch STLport-4.5.3-uclibc.patch "STLport-4.5.3"
		;;
	3.3*)
		apply_patch gcc-3.3.2-coldfire-targets.patch "$GCC"
		apply_patch gcc-3.3.2-coldfire-frame.patch "$GCC"
		apply_patch gcc-3.3.2-uclinux-idshlib.patch "$GCC"
		apply_patch gcc-3.3.2-uclinux-thunk.patch "$GCC"
		apply_patch gcc-3.3.2-uclinux-specs.patch "$GCC"
		apply_patch gcc-3.3.2-coldfire-omitfrmptr.patch "$GCC"
		apply_patch gcc-3.3.2-libstdc++-nowchar.patch "$GCC"
		apply_patch uClibc-gcc332fix.patch "$UCLIBC"
		;;
	3.4*)
		apply_patch gcc-3.4-coldfire-2regoffset.patch "$GCC"
		apply_patch gcc-3.4-output_mi_thunk.patch "$GCC"
		apply_patch gcc-3.4-addsi3_5200.patch "$GCC"
		apply_patch gcc-3.4.0-arm-multilib.patch "$GCC"
		apply_patch gcc-3.4.0-arm-deflibspec.patch "$GCC"
		;;
	3.5*)
		apply_patch gcc-3.4-output_mi_thunk.patch "$GCC"
		apply_patch gcc-3.4-addsi3_5200.patch "$GCC"
		;;
	*)
		echo >&2 "Unsupported GCC version ${GCCVERS}"
		exit 1
		;;
	esac

	case  "${TARGET}" in
	m68k-*)
		extract m68k-bdm-${BDMVERS}.tar*
		apply_patch m68k-bdm-${BDMVERS}/gdb/patches/gdb-${GDBVERS}-bdm-m68k.patch "$GDB"
		case "${GDB}" in
		*insight-*)
			apply_patch m68k-bdm-${BDMVERS}/gdb/patches/insight-${GDBVERS}.patch "$GDB"
			;;
		esac
		;;
	esac

	case "${GDB}" in
	*insight-*)
		apply_patch insight-cygwin.patch "$GDB"
		;;
	esac


	# Get GCC version again using the extracted source
	gcc_version_setup

	# We can now safely uninstall previous installations
	clean_uninstall

	mark 1
}

#############################################################
#
# build binutils
#

stage2()
{
	schk 2 || return 0

	rm -rf ${TARGET}-binutils
	mkdir ${TARGET}-binutils
	cd ${TARGET}-binutils
	${BINUTILS}/configure ${HOST_TARGET} \
		--target=${TARGET} --disable-nls ${PREFIXOPT}
	${MAKE}
	${MAKE} install

	cd ${BASEDIR}
	mark 2
}

#############################################################
#
# build elf2flt
#

stage3()
{
	schk 3 || return 0

	rm -rf ${TARGET}-elf2flt
	mkdir ${TARGET}-elf2flt
	cd ${TARGET}-elf2flt
	${ELF2FLT}/configure ${HOST_TARGET} \
		--with-libbfd=${BASEDIR}/${TARGET}-binutils/bfd/libbfd.a \
		--with-libiberty=${BASEDIR}/${TARGET}-binutils/libiberty/libiberty.a \
		--with-bfd-include-dir=${BASEDIR}/${TARGET}-binutils/bfd \
		--with-binutils-include-dir=${BINUTILS}/include \
		--target=${TARGET} ${PREFIXOPT}
	${MAKE}
	${MAKE} install

	cd $BASEDIR
	mark 3
}

#############################################################
#
# common uClibc Config substitutions
#
# fix_uclibc_config pic_flag shlib_flag
fix_uclibc_config()
{
	pic=$1
	shlib=$2
	(grep -v KERNEL_SOURCE; echo "KERNEL_SOURCE=\"${KERNEL}\"") |
	if [ "${NOMMU}" ]; then
		egrep -v '(UCLIBC_HAS_MMU|BUILD_UCLIBC_LDSO)' |
			egrep -v '(HAS_SHADOW|\<MALLOC\>|UNIX98PTY_ONLY|UCLIBC_CTOR_DTOR)' |
			egrep -v '(DOPIC|UCLIBC_DYNAMIC_ATEXIT|UCLIBC_MALLOC_DEBUGGING)' |
			egrep -v '(UCLIBC_HAS_WCHAR|UCLIBC_HAS_LOCALE|UCLIBC_HAS_TM_EXTENSIONS)' |
			egrep -v '(ADD_LIBGCC_FUNCTIONS|UCLIBC_HAS_THREADS|UCLIBC_PROFILING)' |
			egrep -v '(UCLIBC_HAS_RPC|UCLIBC_HAS_LFS)'

		echo '# UCLIBC_HAS_MMU is not set'
		if [ x"$pic" = x"true" ] ; then
			echo 'DOPIC=y'
		else
			echo '# DOPIC is not set'
		fi
		echo '# BUILD_UCLIBC_LDSO is not set'
		echo '# HAS_SHADOW is not set'
		echo 'MALLOC=y'
		echo '# MALLOC_930716 is not set'
		echo '# UNIX98PTY_ONLY is not set'
		echo 'UCLIBC_CTOR_DTOR=y'
		echo 'UCLIBC_DYNAMIC_ATEXIT=y'
		echo '# UCLIBC_MALLOC_DEBUGGING is not set'
		case "${GCCVERS}" in
		2.95.*)
			echo 'UCLIBC_HAS_WCHAR=y'
			;;
		*)
			echo '# UCLIBC_HAS_WCHAR is not set'
			;;
		esac
		echo '# UCLIBC_HAS_LOCALE is not set'
		echo '# UCLIBC_HAS_TM_EXTENSIONS is not set'
		echo '# ADD_LIBGCC_FUNCTIONS is not set'
#		echo '# UCLIBC_HAS_THREADS is not set'
		echo 'UCLIBC_HAS_THREADS=y'
		echo '# UCLIBC_PROFILING is not set'
		echo '# UCLIBC_HAS_RPC is not set'
		echo '# UCLIBC_HAS_LFS is not set'
	else
		cat
	fi
}

#############################################################

multilib_table()
{
	case "${_CPU}" in
	m68k*) ALL_BUILDS="-Wa,--bitwise-or" ;;
	esac

	ALL_BUILDS="${ALL_BUILDS} -I${KERNEL}/include"

	# Build uClibc with no flags for top-level directory (needed for GCC build, will be removed later)
	echo ". false false $ALL_BUILDS"

	case "${_CPU}" in
	m68k*)
		case "$GCCVERS" in
		2.95*)
			#     GCC multilib subdir       pic   shlib flags
			echo "msoft-float               false false $ALL_BUILDS -D__linux__=1 -msoft-float"

			echo "m5200                     false false $ALL_BUILDS -D__linux__=1 -m5200 -Wa,-m5200"
			echo "m5200/msep-data           true  false $ALL_BUILDS -D__linux__=1 -m5200 -Wa,-m5200 -msep-data"
			echo "m5200/mid-shared-library  true  true  $ALL_BUILDS -D__linux__=1 -m5200 -Wa,-m5200 -mid-shared-library"

			echo "m5307                     false false $ALL_BUILDS -D__linux__=1 -m5307 -Wa,-m5307"
			echo "m5307/msep-data           true  false $ALL_BUILDS -D__linux__=1 -m5307 -Wa,-m5307 -msep-data"
			echo "m5307/mid-shared-library  true  true  $ALL_BUILDS -D__linux__=1 -m5307 -Wa,-m5307 -mid-shared-library"

			echo "m68000                    false false $ALL_BUILDS -D__linux__=1 -m68000"
			echo "m68000/msep-data          true  false $ALL_BUILDS -D__linux__=1 -m68000 -msep-data"
			echo "m68000/mid-shared-library true  true  $ALL_BUILDS -D__linux__=1 -m68000 -Wa,-m68000 -mid-shared-library"

			echo "mcpu32                    false false $ALL_BUILDS -D__linux__=1 -mcpu32"
			;;
		3.*)
			#     GCC multilib subdir       pic   shlib flags
			echo "m5200                     false false $ALL_BUILDS -m5200"
			echo "m5200/msep-data           true  false $ALL_BUILDS -m5200 -msep-data"
			echo "m5200/mid-shared-library  true  true  $ALL_BUILDS -m5200 -mid-shared-library"

			echo "m5206e                    false false $ALL_BUILDS -m5206e"
			echo "m5206e/msep-data          true  false $ALL_BUILDS -m5206e -msep-data"
			echo "m5206e/mid-shared-library true  true  $ALL_BUILDS -m5206e -mid-shared-library"

			echo "m528x                     false false $ALL_BUILDS -m528x"
			echo "m528x/msep-data           true  false $ALL_BUILDS -m528x -msep-data"
			echo "m528x/mid-shared-library  true  true  $ALL_BUILDS -m528x -mid-shared-library"

			echo "m5307                     false false $ALL_BUILDS -m5307"
			echo "m5307/msep-data           true  false $ALL_BUILDS -m5307 -msep-data"
			echo "m5307/mid-shared-library  true  true  $ALL_BUILDS -m5307 -mid-shared-library"

			echo "m5407                     false false $ALL_BUILDS -m5407"
			echo "m5407/msep-data           true  false $ALL_BUILDS -m5407 -msep-data"
			echo "m5407/mid-shared-library  true  true  $ALL_BUILDS -m5407 -mid-shared-library"

			echo "m68000                    false false $ALL_BUILDS -m68000"

			echo "mcpu32                    false false $ALL_BUILDS -mcpu32"
			echo "mcpu32/msep-data          true  false $ALL_BUILDS -mcpu32 -msep-data"
			echo "mcpu32/mid-shared-library true  true  $ALL_BUILDS -mcpu32 -mid-shared-library"
			;;
		*)
			echo >&2 "Unsupported GCC version ${GCCVERS}"
			exit 1
			;;
		esac
		;;
	arm*)
		case "$GCCVERS" in
		2.95*)
			#     GCC multilib subdir                        pic   shlib flags
			echo "fpic                                       true  false $ALL_BUILDS -fpic"
			echo "fpic/msingle-pic-base                      true  false $ALL_BUILDS -fpic -msingle-pic-base"
			echo "mapcs-26                                   false false $ALL_BUILDS -mapcs-26"
			echo "fpic/mapcs-26                              true  false $ALL_BUILDS -fpic -mapcs-26"
			echo "fpic/mapcs-26/msingle-pic-base             true  false $ALL_BUILDS -fpic -mapcs-26 -msingle-pic-base"
			echo "mbig-endian/fpic                           true  false $ALL_BUILDS -fpic -mbig-endian"
			echo "mbig-endian/fpic/msingle-pic-base          true  false $ALL_BUILDS -fpic -mbig-endian -msingle-pic-base"
			echo "mbig-endian/mapcs-26                       false false $ALL_BUILDS -mapcs-26 -mbig-endian"
			echo "mbig-endian/fpic/mapcs-26                  true  false $ALL_BUILDS -fpic -mapcs-26 -mbig-endian"
			echo "mbig-endian/fpic/mapcs-26/msingle-pic-base true  false $ALL_BUILDS -fpic -mapcs-26 -msingle-pic-base -mbig-endian"
			;;
		3.*)
			#     GCC multilib subdir                        pic   shlib flags
			echo "fpic                                       true  false $ALL_BUILDS -fpic"
			echo "fpic/msingle-pic-base                      true  false $ALL_BUILDS -fpic -msingle-pic-base"
			echo "fpic/msingle-pic-base/soft-float           true  false $ALL_BUILDS -msoft-float -fpic -msingle-pic-base" 
#			echo "mbig-endian/fpic                           true  false $ALL_BUILDS -fpic -mbig-endian"
#			echo "mbig-endian/mfpic/msingle-pic-base         true  false $ALL_BUILDS -fpic -mbig-endian -msingle-pic-base"
			echo "mlittle-endian                             true  false $ALL_BUILDS -mlittle-endian"
		        echo "mlittle-endian/fpic                        true  false $ALL_BUILDS -fpic -mlittle-endian"
			;;
		esac
		;;
	esac
}

#############################################################
#
# hack the env up for gcc build
#

stage4()
{
	schk 4 || return 0
	# set -x

	#
	# fix up the uClibc auto gen files
	#
	cd ${UCLIBC}

	echo "bernie: $UCLIBC_CONFIG"
	fix_uclibc_config false false < "$UCLIBC_CONFIG" > .config
	rm -f ${KERNEL}/include/asm
	rm -f ${KERNEL}/include/asm-${_CPU}${NOMMU}/proc
	rm -f ${KERNEL}/include/asm-${_CPU}${NOMMU}/arch
	ln -s ${KERNEL}/include/asm-${_CPU}${NOMMU} ${KERNEL}/include/asm
	${MAKE} oldconfig CROSS="${TARGET}-" TARGET_ARCH=${_CPU}
	${MAKE} headers CROSS="${TARGET}-" TARGET_ARCH=${_CPU}
	chmod 644 include/bits/uClibc_config.h

	rm -rf ${PREFIX}/${TARGET}/${sysinclude}
	rm -f ${UCLIBC}/include/asm
	cp_Lr ${UCLIBC}/include ${PREFIX}/${TARGET}/${sysinclude}
	rm -rf ${PREFIX}/${TARGET}/${sysinclude}/asm
	rm -rf ${PREFIX}/${TARGET}/${sysinclude}/bits
	cp_Lr ${UCLIBC}/include/bits ${PREFIX}/${TARGET}/${sysinclude}/bits
	# cp -r ${UCLIBC}/libc/sysdeps/linux/${_CPU}/bits ${PREFIX}/${TARGET}/${sysinclude}/.
	# cp include/bits/uClibc_config.h ${PREFIX}/${TARGET}/${sysinclude}/bits/.
	rm -rf ${PREFIX}/${TARGET}/${sysinclude}/linux
	cp_Lr ${KERNEL}/include/linux ${PREFIX}/${TARGET}/${sysinclude}/linux
	touch ${PREFIX}/${TARGET}/${sysinclude}/linux/autoconf.h
	cp_Lr ${KERNEL}/include/asm-${_CPU}${NOMMU} \
			${PREFIX}/${TARGET}/${sysinclude}/asm-${_CPU}${NOMMU}

	# 2.4 headers also need this (may not be there for some archs)
	cp_Lr ${KERNEL}/include/asm-${_CPU} \
			${PREFIX}/${TARGET}/${sysinclude}/asm-${_CPU}  || true
	ln -s ${PREFIX}/${TARGET}/${sysinclude}/asm-${_CPU}${NOMMU} \
			${PREFIX}/${TARGET}/${sysinclude}/asm

	case ${TARGET} in
	arm*)
		ln -s ${PREFIX}/${TARGET}/${sysinclude}/asm-${_CPU}${NOMMU}/arch-atmel \
				${PREFIX}/${TARGET}/${sysinclude}/asm/arch
		ln -s ${PREFIX}/${TARGET}/${sysinclude}/asm-${_CPU}${NOMMU}/proc-armv \
				${PREFIX}/${TARGET}/${sysinclude}/asm/proc
		;;
	esac

	#
	# clean out any CVS files,  don't fail on this one
	#
	set +e
	find ${PREFIX}/${TARGET}/${sysinclude} -name CVS | xargs rm -rf
	set -e

	case  "${GCCVERS}" in
	2.95.3)
		mkdir -p ${GCCLIB} || true
		chmod 755 ${GCCLIB}
		;;
	esac

	cd $BASEDIR
	mark 4
}

#############################################################
#
# Just the C compiler so we can build uClibc
#

stage5()
{
	schk 5 || return 0

	rm -rf ${TARGET}-gcc
	mkdir ${TARGET}-gcc
	cd ${TARGET}-gcc

	${GCC}/configure ${HOST_TARGET} \
			--enable-languages=c \
			--disable-libmudflap \
			--disable-nls \
			--target=${TARGET} ${PREFIXOPT}

	case "$GCCVERS" in
	2.95*)
		# Workaround for a bug in GCC 2.95 makefiles
		# (host CFLAGS are being used for target!)
		${MAKE} CFLAGS=
		;;
	*)
		${MAKE}
		;;
	esac
	${MAKE} install

	cd ${BASEDIR}
	mark 5
}

#############################################################
#
# build uClibc multilibs with first pass compiler
#

stage6()
{
	schk 6 || return 0
	# set -x

	cd ${UCLIBC}
	${MAKE} distclean
	rm -f ${KERNEL}/include/asm/proc
	rm -f ${KERNEL}/include/asm/arch
	rm -f ${KERNEL}/include/asm
	ln -s ${KERNEL}/include/asm-${_CPU}${NOMMU} ${KERNEL}/include/asm
	case ${TARGET} in
	arm*)
		ln -s ${KERNEL}/include/asm-${_CPU}${NOMMU}/arch-atmel \
				${KERNEL}/include/asm/arch
		ln -s ${KERNEL}/include/asm-${_CPU}${NOMMU}/proc-armv \
				${KERNEL}/include/asm/proc
		;;
	esac
	rm -rf include/config
	mkdir include/config
	touch include/config/autoconf.h

	multilib_table | while read mlibdir pic shlib cflags
	do
		fix_uclibc_config $pic $shlib < $UCLIBC_CONFIG > .config

		if [ x"$shlib" = x"true" ] ; then
			# uClibc wants these to build shared version
			CONFIG_BINFMT_SHARED_FLAT=y
			export CONFIG_BINFMT_SHARED_FLAT
			OBJCOPY=${TARGET}-objcopy
			export OBJCOPY
			export ROOTDIR
		fi

		${MAKE} oldconfig CROSS="${TARGET}-" TARGET_ARCH=${_CPU} </dev/null || exit 1
		${MAKE} clean     CROSS="${TARGET}-" TARGET_ARCH=${_CPU} || true
		${MAKE} all       CROSS="${TARGET}-" TARGET_ARCH=${_CPU} ARCH_CFLAGS="${cflags}" </dev/null || exit 1

		destdir=${PREFIX}/${TARGET}/lib/$mlibdir
		mkdir -p $destdir
		cp lib/crt0.o $destdir/crt0.o || exit 1
		cp lib/libc.a $destdir/libc.a || exit 1
		cp lib/libcrypt.a $destdir/libcrypt.a || exit 1
		cp lib/libm.a $destdir/libm.a || exit 1
		cp lib/libresolv.a $destdir/libresolv.a || exit 1
		cp lib/libutil.a $destdir/libutil.a || exit 1
		if [ -f lib/libpthread.a ] ; then
			cp lib/libpthread.a $destdir/libpthread.a || exit 1
		fi
		if [ x"$shlib" = x"true" ] ; then
			cp -fa lib/libc $destdir/ || exit 1
			cp -fa lib/libc.gdb $destdir/ || exit 1
		fi

		chmod 644 $destdir/libc.a || exit 1
		chmod 644 $destdir/crt0.o || exit 1

	done || exit 1

	rm -rf include/config

	cd $BASEDIR
	mark 6
}

#############################################################
#
# Rebuild gcc with everything
#

stage7()
{
	schk 7 || return 0

	#
	# Fixes from uClibc/buildroot/make/gcc_target.mk
	#
	case "${GCCVERS}" in
	2.95*)
		# We don't build libstdc++
		;;
	3.3*)
		perl -i -p -e "s,defined.*_GLIBCPP_USE_C99.*,1,g;" ${GCC}/libstdc++-v3/config/locale/generic/c_locale.cc;
		cd ${GCC}/libstdc++-v3/config/os/generic
		cp ctype_base.h ctype_inline.h ctype_noninline.h ../newlib/
		cd ${BASEDIR}
		;;
	3.[45]*)
		# These hacks are really ugly
		perl -i -p -e "s,defined.*_GLIBCXX_USE_C99.*,1,g;" ${GCC}/libstdc++-v3/config/locale/generic/c_locale.cc;
		cd ${GCC}/libstdc++-v3/config/os/generic
		cp ctype_base.h ctype_inline.h ctype_noninline.h ../gnu-linux/
		cd ${BASEDIR}
		;;
	*)
		echo >&2 "Unsupported GCC version ${GCCVERS}"
		exit 1
		;;
	esac

	rm -rf ${TARGET}-gcc
	mkdir ${TARGET}-gcc
	cd ${TARGET}-gcc

	case "${TARGET}" in
	arm-*)
		# create if not there
		ar rv ${PREFIX}/${TARGET}/lib/libg.a
		;;
	esac

	case "${GCCVERS}" in
	2.95.*)
		${GCC}/configure ${HOST_TARGET} \
			--enable-languages=c,c++ \
			--target=${TARGET} \
			${PREFIXOPT} \
			--enable-multilib \
			--enable-target-optspace \
			--disable-checking \
			--with-gnu-ld \
			--disable-nls \
			--with-gxx-include-dir=${PREFIX}/${TARGET}/stlport

		cflags='-Os -Dlinux -D__linux__ -Dunix'
		${MAKE} LIBS=-lc CFLAGS="${cflags}" CXXFLAGS="${cflags}"
		;;
	3.3*)
		# NOTE: flags passed with --enable-cxx-flags are needed to import
		# some required functions from uClibc headers when building libstdc++
		#
		# NOTE: non auto-confiscated top-level configure script in GCC 3.3.x
		# has quoting bugs with --enable-cxx-flags
		#
		CFLAGS="-DDWARF2_UNWIND_INFO=0 $CFLAGS" \
		${GCC}/configure ${HOST_TARGET} \
			--target=${TARGET} \
			${PREFIXOPT} \
			--enable-languages=c,c++ \
			--enable-multilib \
			--enable-target-optspace \
			--with-gnu-ld \
			--disable-nls \
			--disable-__cxa_atexit \
			--disable-c99 \
			--disable-clocale \
			--disable-c-mbchar \
			--disable-long-long \
			--enable-cxx-flags="\\\"-D_ISOC99_SOURCE -D_BSD_SOURCE\\\""

		${MAKE}
		;;
	3.[45]*)
		# NOTE: flags passed with --enable-cxx-flags are needed to import
		# some required functions from uClibc headers when building libstdc++
		#
		CFLAGS="-DDWARF2_UNWIND_INFO=0 $CFLAGS" \
		${GCC}/configure ${HOST_TARGET} \
			--target=${TARGET} \
			${PREFIXOPT} \
			--enable-languages=c,c++ \
			--enable-multilib \
			--enable-target-optspace \
			--with-gnu-ld \
			--disable-nls \
			--disable-__cxa_atexit \
			--disable-c99 \
			--disable-clocale \
			--disable-c-mbchar \
			--disable-long-long \
			--enable-threads=posix \
			--enable-cxx-flags='-D_ISOC99_SOURCE -D_BSD_SOURCE'

		${MAKE}
		;;
	*)
		echo >&2 "Unsupported GCC version ${GCCVERS}"
		exit 1
		;;
	esac

	${MAKE} install

	#
	# The _ctors.o file included in libgcc causes all kinds of random pain
	# sometimes it gets included and sometimes it doesn't.  By removing it
	# and using a good linker script (ala elf2flt.ld) all will be happy
	#
	find ${GCCLIB} -name libgcc.a -print | while read t
		do
			${TARGET}-ar dv "$t" _ctors.o
		done

	#
	# Don't leave these around as they will not work for all targets
	# the proper ones get built later in stage9/stageA
	#
	rm -f \
		${PREFIX}/${TARGET}/lib/crt0.o \
		${PREFIX}/${TARGET}/lib/libc.a \
		${PREFIX}/${TARGET}/lib/libm.a \
		${PREFIX}/${TARGET}/lib/libutil.a \
		${PREFIX}/${TARGET}/lib/libpthread.a \
		${PREFIX}/${TARGET}/lib/libcrypt.a \
		${PREFIX}/${TARGET}/lib/libresolv.a \
		${PREFIX}/${TARGET}/lib/libiberty.a \
		${PREFIX}/${TARGET}/lib/libstdc++.a \
		${PREFIX}/${TARGET}/lib/libsupc++.a \

#FIXME		${PREFIX}/${TARGET}/lib/*.la

	cd $BASEDIR
	mark 7
}

#############################################################
#
# build the STLport stuff,  and install it
#

stage8()
{
	schk 8 || return 0
	# set -x

	if [ x"${GCCVERS}" != x"2.95.3" ] ; then
		mark 8
		return 0
	fi

	cd $BASEDIR/STLport-4.5.3/src
	multilib_table | while read mlibdir pic cflags
	do
		${MAKE} -f gcc-uclinux-elf.mak ARCH=${_CPU} PREFIX=${PREFIX} \
				CROSS=${TARGET}- clean
		${MAKE} -f gcc-uclinux-elf.mak ARCH=${_CPU} PREFIX=${PREFIX} \
				CROSS=${TARGET}- ARCH_CFLAGS="${cflags}" all || exit 1
		cp ../lib/libstdc++.a ${PREFIX}/${TARGET}/lib/$mlibdir/. || exit 1
	done || exit 1

	rm -rf ${PREFIX}/${TARGET}/stlport
	cp -a ../stlport ${PREFIX}/${TARGET}/.

	cd $BASEDIR
	mark 8
}

#############################################################
#
# build genromfs
#

stage9()
{
	schk 9 || return 0
	rm -rf genromfs-0.5.1
	extract genromfs-0.5.1.*
	cd genromfs-0.5.1
	if [ "${CYGWIN}" ]; then
		${PATCH} -p1 < ../genromfs-0.5.1-cygwin-020605.patch
	fi
	${MAKE}
	cp genromfs${EXE} ${PREFIX}/bin/.
	chmod 755 ${PREFIX}/bin/genromfs${EXE}

	cd $BASEDIR
	mark 9
}

#############################################################
#
# build BDM driver (only for m68k-*)
#

stageA()
{
	schk A || return 0

	case "${TARGET}" in
	m68k-*)
		rm -rf ${BDM}-build
		mkdir -p ${BDM}-build || true
		cd ${BDM}-build
		# Some BFD headers include stuff from the top-level include dir
		CPPFLAGS="-I${BINUTILS}/include" \
		${BDM}/configure \
			--with-bfd-include-dir=${BASEDIR}/${TARGET}-binutils/bfd \
			--with-libbfd=${BASEDIR}/${TARGET}-binutils/bfd/libbfd.a \
			--with-libiberty=${BASEDIR}/${TARGET}-binutils/libiberty/libiberty.a \
			${PREFIXOPT}
		${MAKE}
		${MAKE} install
		cd ${BASEDIR}
		;;
	esac

	cd $BASEDIR
	mark A
}

#############################################################
#
# build cross GDB (with BDM support for m68k-*)
#

stageB()
{
	schk B || return 0

	rm -rf ${TARGET}-gdb
	mkdir ${TARGET}-gdb
	cd ${TARGET}-gdb

	# Add include path for BDM headers
	CFLAGS="$CFLAGS -I${PREFIX}/include" \
	${GDB}/configure \
		--enable-tui \
		--enable-gdbmi \
		--enable-gdbcli \
		--target=${GDBTARGET} \
		--prefix=${GDBPREFIX}
	${MAKE}
	${MAKE} install

	if [ "${GDBPREFIX}" != "${PREFIX}" ] ; then
		# Make some handy links to GDB binaries
		# NOTE: these need be absolute paths for insight to find its stuff!
		ln -sf ${GDBPREFIX}/bin/${GDBTARGET}-gdb${EXE} ${PREFIX}/bin/${GDBTARGET}-gdb${EXE}
		case "${GDB}" in
		*insight-*)
			ln -sf ${GDBPREFIX}/bin/${GDBTARGET}-insight${EXE} ${PREFIX}/bin/${GDBTARGET}-insight${EXE}
			;;
		esac
	fi

	case "${TARGET}" in
	m68k-*)
		# Also create links without the 'bdm-' infix for convenience
		ln -sf ${GDBPREFIX}/bin/${GDBTARGET}-gdb${EXE} ${PREFIX}/bin/${TARGET}-gdb${EXE}
		case "${GDB}" in
		*insight-*)
			ln -sf ${GDBPREFIX}/bin/${GDBTARGET}-insight${EXE} ${PREFIX}/bin/${TARGET}-insight${EXE}
			;;
		esac
		;;
	esac

	cd $BASEDIR
	mark B
}

#############################################################
#
# Add backward compatibility links
#

stageC()
{
	schk C || return 0

	if [ "$TARGET" != "$OLDTARGET" ] ; then
		cd ${PREFIX}/bin
		for file in \
			${TARGET}-addr2line \
			${TARGET}-ar \
			${TARGET}-as \
			${TARGET}-c++filt \
			${TARGET}-elf2flt \
			${TARGET}-flthdr \
			${TARGET}-ld \
			${TARGET}-ld.real \
			${TARGET}-nm \
			${TARGET}-objcopy \
			${TARGET}-objdump \
			${TARGET}-ranlib \
			${TARGET}-readelf \
			${TARGET}-size \
			${TARGET}-strings \
			${TARGET}-strip \
			${TARGET}-gcc \
			${TARGET}-gcov \
			${TARGET}-c++ \
			${TARGET}-g++ \
			${TARGET}-c++filt
		do
			ln -sf "$file" "`echo $file | sed -e "s/${TARGET}/${OLDTARGET}/"`"
		done
	fi

	cd $BASEDIR
	mark C
}


#############################################################
#
# make a self-extracting executable archive out of a tar-bzip
# that optionally pre-cleans the directory and checks a few things.
#
# build_sfx <BASE_NAME> [<CLEAN_FLAG>]
#
build_sfx()
{
	BASE_NAME="$1"
	CLEAN_FLAG=$2
	SH_ARCHIVE="${BASE_NAME}.sh"

	#
	# Create the shell script
	#
	cat <<!EOF > "${SH_ARCHIVE}"
#!/bin/sh

SCRIPT="\$0"
case "\${SCRIPT}" in
/*)
	;;
*)
	if [ -f "\${SCRIPT}" ]
	then
		SCRIPT="\`pwd\`/\${SCRIPT}"
	else
		SCRIPT="\`which \${SCRIPT}\`"
	fi
	;;
esac

cd /

if [ ! -f "\${SCRIPT}" ]
then
	echo "Cannot find the location of the install script (\$SCRIPT)"
	exit 1
fi

if [ ! -d "${PREFIX}" ]; then
	mkdir -p "${PREFIX}"
fi
if [ ! -w "${PREFIX}" ]
then
	echo "You must be root to install these tools."
	exit 1
fi

!EOF

	#
	# Add code to remove obsolete files if needed
	#
	if [ x"${CLEAN_FLAG}" = x"true" ] ; then
		cat <<!EOF >> "${SH_ARCHIVE}"
rm -rf "${GCCLIB}"
rm -f "${PREFIX}/bin/flthdr"
rm -f "${PREFIX}/bin/elf2flt"
rm -f "${PREFIX}/bin/${TARGET}-*"
rm -rf "${PREFIX}/${TARGET}"
!EOF
		if [ "$PREFIX" != "$GDBPREFIX" ] ; then
			cat <<!EOF >> "${SH_ARCHIVE}"
rm -rf "${GDBPREFIX}"
!EOF
		fi
		if [ "${TARGET}" != "$OLDTARGET" ] ; then
			#
			# Clean the mess made by target tuple switch
			#
			cat <<!EOF >> "${SH_ARCHIVE}"
rm -f "${PREFIX}/bin/${OLDTARGET}-*"
rm -rf "${PREFIX}/${OLDTARGET}"
!EOF
		fi
	fi

	#
	# Complete the script with archive extraction
	#
	cat <<!EOF >> "${SH_ARCHIVE}"
SKIP=\`awk '/^__ARCHIVE_FOLLOWS__/ { print NR + 1; exit 0; }' \${SCRIPT}\`
tail +\${SKIP} \${SCRIPT} | bunzip2 | tar xvf -

exit 0
__ARCHIVE_FOLLOWS__
!EOF

	#
	# Append tar archive and make the script executable
	#
	cat "${BASE_NAME}.tar.bz2" >> "${SH_ARCHIVE}"
	chmod 755 "${SH_ARCHIVE}"
	rm "${BASE_NAME}.tar.bz2"
}

#############################################################
#
# tar up everthing we have built
#
build_tar_file()
{
	# set -x
	cd /

	RELEASEDATE=`date +%Y%m%d`
	GCCVERS_SHORT="gcc${GCCVERS%%-*}"
	DIST_BASE="${BASEDIR}/${TARGET}-tools-base-${GCCVERS_SHORT}-${CYGWIN}${RELEASEDATE}"
	DIST_CXX="${BASEDIR}/${TARGET}-tools-c++-${GCCVERS_SHORT}-${CYGWIN}${RELEASEDATE}"
	DIST_GDB="${BASEDIR}/${TARGET}-tools-gdb-${CYGWIN}${RELEASEDATE}"

	EXTRAS=
	if [ ! -z "${GCCLIBEXEC}" ]
	then
		EXTRAS="${EXTRAS} .${GCCLIBEXEC}"
		strip ${GCCLIBEXEC}/* > /dev/null 2>&1 || true
	fi

	if [ "${TARGET}" != "${OLDTARGET}" ] ; then
		EXTRAS="${EXTRAS} .${PREFIX}/bin/${OLDTARGET}-*"
	fi

	GDBEXTRAS=
	if [ -e "${GDBPREFIX}"/bin/m68k-bdm-elf-gdbtui${EXE} ] ; then
		GDBEXTRAS="${GDBEXTRAS} .$GDBPREFIX/bin/m68k-bdm-elf-gdbtui${EXE}"
	fi
	case "${GDB}" in
	*insight-*)
		GDBEXTRAS="${GDBEXTRAS} .${PREFIX}/bin/${TARGET}-insight${EXE}"
		;;
	esac
	if [ "${PREFIX}" != "${GDBPREFIX}" ] ; then
		GDBEXTRAS="${GDBEXTRAS} .${GDBPREFIX}"
	fi
	case "${TARGET}" in
	m68k*)
		if [ -e ".${PREFIX}/bin/m68k-bdm-elf-gdb${EXE}" ]
		then
			GDBEXTRAS="${GDBEXTRAS} .${PREFIX}/bin/m68k-bdm-elf-gdb${EXE}"
			case "${GDB}" in
			*insight-*)
				GDBEXTRAS="${GDBEXTRAS} .${PREFIX}/bin/m68k-bdm-elf-insight${EXE}"
				;;
			esac
			GDBEXTRAS="${GDBEXTRAS} .${PREFIX}/bin/bdmreset${EXE}"
			GDBEXTRAS="${GDBEXTRAS} .${PREFIX}/bin/bdmctrl${EXE}"
			GDBEXTRAS="${GDBEXTRAS} .${PREFIX}/bin/bdmflash${EXE}"
			GDBEXTRAS="${GDBEXTRAS} .${PREFIX}/bin/bdmmon${EXE}"
			GDBEXTRAS="${GDBEXTRAS} .${PREFIX}/bin/bdm-chk${EXE}"
			GDBEXTRAS="${GDBEXTRAS} .${PREFIX}/bin/bdm-cpu32-chk${EXE}"
			GDBEXTRAS="${GDBEXTRAS} .${PREFIX}/sbin/bdmd${EXE}"
		fi
		;;
	esac

	#
	# strip the binaries,  make sure we don't strip the
	# libraries -- some platforms allow this :-(
	#
	strip ${PREFIX}/bin/genromfs${EXE} > /dev/null 2>&1 || true
	strip ${PREFIX}/bin/${TARGET}-* > /dev/null 2>&1 || true
	strip ${PREFIX}/${TARGET}/bin/* > /dev/null 2>&1 || true
	strip ${GCCLIB}/*[!ao] > /dev/null 2>&1 || true
	strip "${GDBPREFIX}"/bin/${TARGET}-{gdb,insight}${EXE} > /dev/null 2>&1 || true

	#
	# Remove GDB's TCL crap
	#
	if [ "${GDBPREFIX}" != "${PREFIX}" ] ; then
		rm -rf ${GDBPREFIX}/include
		rm -rf ${GDBPREFIX}/info
		rm -rf ${GDBPREFIX}/man
	fi

	#
	# tar it all up
	#
	tar -cvjf "${DIST_BASE}.tar.bz2" \
		".${GCCLIB}" \
		".${PREFIX}/${TARGET}" \
		.${PREFIX}/bin/${TARGET}-* \
		".${PREFIX}/bin/genromfs${EXE}" \
		".${PREFIX}/bin/${TARGET}-elf2flt${EXE}" \
		".${PREFIX}/bin/${TARGET}-flthdr${EXE}" \
		${EXTRAS} \
		--exclude 'libstdc++.*' \
		--exclude 'libsupc++.*'
	build_sfx ${DIST_BASE} true

	tar -cvjf "${DIST_CXX}.tar.bz2" \
		".${GLIBCXXHEADERS}" \
		`find .${PREFIX}/${TARGET}/lib -name "lib*c++*"`
	build_sfx ${DIST_CXX} false

	tar -cvjf "${DIST_GDB}.tar.bz2" \
		".${PREFIX}/bin/${TARGET}-gdb${EXE}" \
		${GDBEXTRAS}
	build_sfx ${DIST_GDB} false

	cd $BASEDIR
}


#############################################################
#
# main - put everything together in order.
#
# Some setup
#

case ${TARGET} in
m68k*) _CPU=m68k; NOMMU=nommu ;;
arm*)  _CPU=arm;  NOMMU=nommu ;;
esac

#
# If not defined use the GNU tools default of /usr/local
#
if [ -z "${PREFIX}" ]; then
	PREFIX=/usr/local/${_CPU}-uclinux-tools
fi

PATH="${PREFIX}/bin:$PATH"; export PATH
PREFIXOPT="--prefix=${PREFIX}"

#
# This may fail until we've extracted GCC source.
# Will be redone later in stage1.
#
gcc_version_setup

#
# Handle GDB target and installation directory
#
case "${TARGET}" in
m68k-*)
	# Build BDM enabled version of GDB
	GDBTARGET="m68k-bdm-elf"
	;;
*)
	GDBTARGET="${TARGET}"
	;;
esac

#
# Can't set prefix to ${PREFIX}/${TARGET} because
# autoconf would use the uClibc headers :-(
#
#GDBPREFIX=${PREFIX}/${TARGET}-gdb
GDBPREFIX=${PREFIX}

#
# Choose config file for uClibc, either externally provieded or
# uClibc's default
#
UCLIBC_CONFIG="${BASEDIR}/uClibc-${UCLIBCVERS}-${_CPU}.config"
if [ ! -f "$UCLIBC_CONFIG" ]
then
	UCLIBC_CONFIG="${UCLIBC}/extra/Configs/Config.${_CPU}.default"
fi

#
# setup some Cygwin changes
#
if uname -o 2>/dev/null | grep -i "Cygwin" >/dev/null
then
	CYGWIN=cygwin-
	EXE=".exe"
	HOST_TARGET="--host=i386-pc-cygwin32"
else
	EXE=""
	HOST_TARGET=""
fi

#
# first check some args
#

case "$1" in
build)
	rm -f $BASEDIR/STAGE*
	;;
continue)
	# do nothing here
	;;
dist|tar)
	build_tar_file
	exit 0
	;;
clean)
	clean_all
	exit 0
	;;
uninstall)
	clean_uninstall
	exit 0
	;;
*)
	echo "Usage: $0 (build|continue|dist|clean|uninstall)" >&2
	echo "    build      build everything from scratch."
	echo "    continue   continue building from last error."
	echo "    dist       build binary archive for distribution."
	echo "    clean      clean all temporary files."
	echo "    uninstall  uninstall toolchain."
	exit 1
	;;
esac

#
# You have to root for this one
#

if [ ! -d "${PREFIX}" ]; then
	mkdir -p "${PREFIX}"
fi

if [ ! -w "${PREFIX}" ]; then
	echo "Bad, PREFIX (${PREFIX}) is not writable! Perhaps you forgot to become root?"
	exit 1
fi

if [ ! -f "${ROOTDIR}/Makefile" -a ${TARGET} = m68k-elf ]; then
	echo "Bad, ROOTDIR (${ROOTDIR}) does not seem to contain an uClinux tree."
	echo "The uClinux tree is required when building uClibc as an id-based shared library."
	exit 1
fi

if [ ! -f ${KERNEL}/include/linux/version.h -o \
		! -f ${KERNEL}/include/linux/autoconf.h ]; then
	echo "Your kernel is not configured, cannot continue." >&2
	echo "The following files do not exist:"
	echo
	echo "    ${KERNEL}/include/linux/version.h"
	echo "    ${KERNEL}/include/linux/autoconf.h"
	echo
	echo "These are need by the build.  You should do the following:"
	echo
	echo "    cd ${KERNEL}"
	echo "    make ARCH=${_CPU}${NOMMU} oldconfig"
	echo "    make dep"
	echo
	echo "You should then be able to continue."
	exit 1
fi

# set -x	# debug script
set -e		# if anything fails, stop

stage1
stage2
stage3
stage4
stage5
stage6
stage7
stage8
stage9
stageA
stageB
stageC

echo "--------------------------------------------------------"
echo "Build successful !"
echo "--------------------------------------------------------"

#############################################################

