#!/bin/bash
#
# Build a gcc + uClibc toolchain
#
# This script implements the recommended process for building a cross-compiling
# gcc circa late 2007 (see http://gcc.gnu.org/ml/gcc/2007-08/msg00327.html).

set -ex

unset uclibc binutils gcc gmp mpfr kernel_headers arch mflags destdir
source builddefs.sh

sysroot=$(pwd)/sysroot

unset CPATH LIBRARY_PATH INSTALL
PATH=/usr/lib/ccache:/bin:/usr/bin
rm -rf ${sysroot}
mkdir ${sysroot}
ln -s . ${sysroot}/usr

# Link target-specific usr directory to usr, otherwise gcc has trouble finding ld
ln -s . ${sysroot}/usr/${arch}-linux-uclibc

# Install kernel headers
mkdir ${sysroot}/usr/include
cp -pLR ${kernel_headers}/include/{asm,linux,asm-generic} ${sysroot}/usr/include/

# Build gmp library
( cd ${gmp}; ABI=32 ./configure --prefix=/usr )
make -C ${gmp} all install DESTDIR=${sysroot}

# Build mpfr library
( cd ${mpfr}; ./configure --prefix=/usr --with-gmp=${sysroot}/usr )
make -C ${mpfr} all install DESTDIR=${sysroot}

# Build binutils
( cd ${binutils}; ./configure --prefix=/usr --target=${arch}-linux-uclibc --with-gmp=${sysroot}/usr --with-mpfr=${sysroot}/usr --with-sysroot=${sysroot} --program-prefix=${arch}-linux-uclibc- )
make -C ${binutils} all install DESTDIR=${sysroot}

# Build stage 1 gcc (required to build uClibc)
( cd ${gcc}; ./configure --prefix=/usr --target=${arch}-linux-uclibc --enable-languages=c --with-gmp=${sysroot}/usr --with-mpfr=${sysroot}/usr --disable-shared --disable-nls --disable-multilib --disable-threads --disable-libmudflap --disable-libssp --disable-libgomp --with-build-time-tools=${sysroot}/usr/bin --with-gnu-ld )
make -C ${gcc} all-gcc install-gcc DESTDIR=${sysroot}

# Build uClibc
cp uclibc-${arch}.config ${uclibc}/.config
make -C ${uclibc} oldconfig
PATH=${sysroot}/usr/bin:${PATH} make -C ${uclibc} CROSS=${arch}-linux-uclibc- KERNEL_HEADERS=${sysroot}/usr/include PREFIX=${sysroot} RUNTIME_PREFIX=/ DEVEL_PREFIX=/usr/ all install
PATH=${sysroot}/usr/bin:${PATH} make -C ${uclibc}/utils CROSS=${arch}-linux-uclibc- KERNEL_HEADERS=${sysroot}/usr/include PREFIX=${sysroot} RUNTIME_PREFIX=/ DEVEL_PREFIX=/usr/ hostutils utils_install

# Build final gcc targeting uClibc
make -C ${gcc} distclean
( cd ${gcc}; ./configure --prefix=/usr --target=${arch}-linux-uclibc --enable-languages=c --with-sysroot=${sysroot} --disable-nls --disable-multilib --disable-threads --disable-libgomp --with-build-time-tools=${sysroot}/usr/bin --with-gnu-ld )
make -C ${gcc} all install DESTDIR=${sysroot}
