#!/bin/bash
GMPVER=4.2.4
MPFRVER=2.3.2
GCCVER=4.3.2
BINUTILSVER=2.18.50
BINUTILSTARVER=${BINUTILSVER}-20080109-2
TARGETDIR=`pwd`/xgcc

mkdir -p tarballs
if [ ! -f tarballs/gmp-${GMPVER}.tar.bz2 ]; then
	(cd tarballs; wget ftp://ftp.gmplib.org/pub/gmp-${GMPVER}.tar.bz2)
fi
if [ ! -f tarballs/mpfr-${MPFRVER}.tar.bz2 ]; then
	(cd tarballs; wget http://www.mpfr.org/mpfr-current/mpfr-${MPFRVER}.tar.bz2)
fi
if [ ! -f tarballs/gcc-core-${GCCVER}.tar.bz2 ]; then
	(cd tarballs; wget ftp://ftp.gwdg.de/pub/gnu/ftp/gnu/gcc/gcc-${GCCVER}/gcc-core-${GCCVER}.tar.bz2)
fi
if [ ! -f tarballs/binutils-${BINUTILSTARVER}-src.tar.gz ]; then
	(cd tarballs; wget http://switch.dl.sourceforge.net/sourceforge/mingw/binutils-${BINUTILSTARVER}-src.tar.gz)
fi
if [ ! -d gmp-${GMPVER} ]; then
	tar jxvf tarballs/gmp-${GMPVER}.tar.bz2
fi
if [ ! -d mpfr-${MPFRVER} ]; then
	tar jxvf tarballs/mpfr-${MPFRVER}.tar.bz2
fi
if [ ! -d gcc-${GCCVER} ]; then
	tar jxvf tarballs/gcc-core-${GCCVER}.tar.bz2
	patch -N -p0 < use-gnu-style-comments-in-assembly.patch
fi
if [ ! -d binutils-${BINUTILSVER} ]; then
	tar zxvf tarballs/binutils-${BINUTILSTARVER}-src.tar.gz
	patch -N -p0 < no-i386-svr4-asm-comments.patch
fi
if [ ! -d combined ]; then
	mkdir combined
	(cd combined
		ln -s ../gcc-${GCCVER}/* . 2>/dev/null
		ln -s ../binutils-${BINUTILSVER}/* . 2>/dev/null
		rm include
		mkdir include
		cd include
		ln -s ../../gcc-${GCCVER}/include/* . 2>/dev/null
		ln -s ../../binutils-${BINUTILSVER}/include/* . 2>/dev/null
	)
fi
mkdir -p build-gmp build-mpfr build-gcc
(cd build-gmp
	../gmp-${GMPVER}/configure --disable-shared --prefix=$TARGETDIR ABI=32
	make
	make install
)
CFLAGS=`grep __GMP_CFLAGS $TARGETDIR/include/gmp.h |cut -d\" -f2`
test `uname` == "Darwin" && CFLAGS="$CFLAGS -force_cpusubtype_ALL"
(cd build-mpfr
	../mpfr-${MPFRVER}/configure --disable-shared --prefix=$TARGETDIR --with-gmp=$TARGETDIR CFLAGS="$CFLAGS"
	make
	make install
)
(cd build-gcc
	../combined/configure --prefix=$TARGETDIR --target=i386-elf --disable-libssp --disable-bootstrap --with-gmp=$TARGETDIR --with-mpfr=$TARGETDIR CFLAGS="$CFLAGS"
	make
	make install
)
