#!/bin/sh
#
# This script builds and installs binutils, gcc and newlib in the order
# necessary for the whole thing to work.  The present version is based
# on OsmocomBB's gnu-arm-build.2.sh script, which is in turn based on
# yet another source.  The present version has been concocted by
# Spacefalcon the Outlaw for use in the FreeCalypso project.
#
# This script needs to be invoked with two arguments:
#
# $1: the path to the directory containing the upstream binutils, gcc
#     and newlib source tarballs;
#
# $2: the path to the directory where the built toolchain should be
#     installed.
#
# Note that there isn't a single install step at the end, instead this
# script will build and install one component, then proceed to build the
# next component which depends on the previous one, etc.  For this reason
# you should create a dedicated install directory that is writable by your
# regular (non-root) uid, then run this script to populate that directory
# with the toolchain.

if [ $# != 2 ]
then
	echo "usage: $0 path-to-tarballs path-to-install"
	exit 1
fi

set -ex

target_args="--target=arm-elf"

# binutils come first
tar xjf $1/binutils-2.21.1a.tar.bz2
mkdir -p binutils-build
cd binutils-build
../binutils-2.21.1/configure --prefix=$2 ${target_args} --disable-nls
make all
make install
cd ..

# unpack gcc and newlib sources at the same time: the gcc build
# will be pointed to newlib headers
gcc_version=4.5.4
newlib_version=2.0.0
tar xjf $1/gcc-core-${gcc_version}.tar.bz2
tar xzf $1/newlib-${newlib_version}.tar.gz

# gcc depends on binutils - add our install destination dir to the PATH
# we prepend it to avoid surprises if some other arm-elf- toolchain
# happens to be present already
PATH=$2/bin:$PATH
export PATH

mkdir -p gcc-build
cd gcc-build
../gcc-${gcc_version}/configure --prefix=$2 ${target_args} \
	--enable-interwork --enable-multilib \
	--with-cpu=arm7tdmi --with-float=soft \
	--enable-languages=c --with-newlib \
	--with-headers=`pwd`/newlib-${newlib_version}/newlib/libc/include \
	--with-system-zlib --disable-shared \
	--disable-nls
make all-gcc
make install-gcc
cd ..

# now we can build newlib
mkdir newlib-build
cd newlib-build
../newlib-${newlib_version}/configure --prefix=$2 ${target_args} \
	--enable-interwork --enable-multilib \
	--enable-target-optspace --enable-newlib-reent-small \
	--disable-newlib-supplied-syscalls \
	--disable-nls
make all
make install
cd ..

# and finally, libgcc
cd gcc-build
make all
make install
cd ..
