#! /bin/sh

cd $BLDDIR
tar -xf $SRCDIR/gcc-core-$GCC_VER.tar.bz2
tar -xf $SRCDIR/gcc-g++-$GCC_VER.tar.bz2
cd gcc-$GCC_VER

# 4.2.4
patch -p0 < $SRCDIR/patches/gcc-$GCC_VER/gcc-4.2-target-configuration.patch
patch -p1 < $SRCDIR/patches/gcc-$GCC_VER/gcc-4.2.4-specs-1.patch
patch -p1 < $SRCDIR/patches/gcc-$GCC_VER/gcc-4.2.4-cross_search_paths-1.patch

# 4.3.4 - results in non-booting image
#patch -p0 < $SRCDIR/patches/gcc-$GCC_VER/gcc-4.3-rev141004-libgcc-config.patch
#patch -p0 < $SRCDIR/patches/gcc-$GCC_VER/gcc-4.3-rev141722-libgcc-config.patch
#patch -p0 < $SRCDIR/patches/gcc-$GCC_VER/gcc-4.3-rev141838-gcc-config-1.patch
#patch -p1 < $SRCDIR/patches/gcc-$GCC_VER/gcc-4.3.3-specs-1.patch
#patch -p1 < $SRCDIR/patches/gcc-$GCC_VER/pr41818.diff
#patch -p0 < $SRCDIR/patches/gcc-$GCC_VER/gcc-4.3-tlink.patch

# 4.4.2 - results in broken c++ compiler
#patch -p1 < $SRCDIR/patches/gcc-$GCC_VER/pr41818.diff

echo -en '#undef STANDARD_INCLUDE_DIR\n#define STANDARD_INCLUDE_DIR "/tools/include/"\n\n' >> gcc/config/linux.h
echo -en '\n#undef STANDARD_STARTFILE_PREFIX_1\n#define STANDARD_STARTFILE_PREFIX_1 "/tools/lib/"\n' >> gcc/config/linux.h
echo -en '\n#undef STANDARD_STARTFILE_PREFIX_2\n#define STANDARD_STARTFILE_PREFIX_2 ""\n' >> gcc/config/linux.h

cp -v gcc/Makefile.in{,.orig}
sed -e "s@\(^CROSS_SYSTEM_HEADER_DIR =\).*@\1 /tools/include@g" \
    gcc/Makefile.in.orig > gcc/Makefile.in

touch /tools/include/limits.h

cd $BLDDIR
rm -rf cross-gcc-build
mkdir -p cross-gcc-build
cd cross-gcc-build

AR=ar LDFLAGS="-Wl,-rpath,/cross-tools/lib" \
  ../gcc-$GCC_VER/configure --prefix=/cross-tools \
  --build=${CHFS_HOST} --host=${CHFS_HOST} --target=${CHFS_TARGET} \
  --with-sysroot=${CLFS} --with-local-prefix=/tools --disable-nls \
  --disable-shared --with-mpfr=/cross-tools --with-gmp=/cross-tools \
  --without-headers --with-newlib --disable-decimal-float \
  --disable-libgomp --disable-libmudflap --disable-libssp \
  --disable-threads --enable-languages=c --disable-multilib
make all-gcc
make install-gcc

# > 4.3
#  --with-ppl=/cross-tools --with-cloog=/cross-tools \
#make all-gcc all-target-libgcc
#make install-gcc install-target-libgcc
  
# glibc tries to link to this
# CLFS patch to disable libgcc_eh.a linking
#echo '/* Empty.  */' > /tools/lib/libgcc_eh.a

# prepare for pass 2
rm -f config.status config.cache */config.cache */*/config.cache

cd $ROOT
