#!/bin/sh

# This shell script can be used to install the GNU gcc compiler on a
# unix based computer.  The GNU gcc compiler is usually better at
# compiling C code produced by the Gambit Scheme compiler than the
# clang (LLVM) compiler.  This is particularly useful on OS X because
# clang is the C compiler that is provided with recent versions of
# Apple's Xcode.

# After executing:
#
#    ./install-gnu-gcc
#
# you should add this line to your ~/.profile and ~/.bashrc files:
#
#    export PATH=/usr/local/gcc-6.1.0/bin:$PATH

GCCVERSION=6.1.0
GMPVERSION=6.1.0
MPFRVERSION=3.1.4
MPCVERSION=1.0.3
ISLVERSION=0.16.1
CLOOGVERSION=0.18.1

PREFIX=/usr/local/gcc-$GCCVERSION
MAKE="make -j 8"

# Download & install the latest GCC and prerequisites

mkdir temp-gcc
cd temp-gcc

command -v wget >/dev/null 2>&1 || { echo >&2 "This script requires wget but it's not installed.  Aborting."; exit 1; }

wget ftp://ftp.gnu.org/gnu/gcc/gcc-$GCCVERSION/gcc-$GCCVERSION.tar.gz
wget ftp://ftp.gnu.org/gnu/gmp/gmp-$GMPVERSION.tar.bz2
wget ftp://ftp.gnu.org/gnu/mpfr/mpfr-$MPFRVERSION.tar.gz
wget ftp://ftp.gnu.org/gnu/mpc/mpc-$MPCVERSION.tar.gz

tar zxf gcc-$GCCVERSION.tar.gz
tar jxf gmp-$GMPVERSION.tar.bz2
tar zxf mpfr-$MPFRVERSION.tar.gz
tar zxf mpc-$MPCVERSION.tar.gz

ln -s ../gmp-$GMPVERSION   gcc-$GCCVERSION/gmp
ln -s ../mpfr-$MPFRVERSION gcc-$GCCVERSION/mpfr
ln -s ../mpc-$MPCVERSION   gcc-$GCCVERSION/mpc

# The following packages are not absolutely necessary, but they enable
# the Graphite loop optimizations in gcc.

wget ftp://gcc.gnu.org/pub/gcc/infrastructure/isl-$ISLVERSION.tar.bz2
wget ftp://gcc.gnu.org/pub/gcc/infrastructure/cloog-$CLOOGVERSION.tar.gz

tar jxf isl-$ISLVERSION.tar.bz2
tar zxf cloog-$CLOOGVERSION.tar.gz

ln -s ../isl-$ISLVERSION   gcc-$GCCVERSION/isl
ln -s ../cloog-$CLOOGVERSION gcc-$GCCVERSION/cloog

# Do the actual build

mkdir build-dir
cd build-dir
../gcc-$GCCVERSION/configure --prefix=$PREFIX 
$MAKE 

sudo mkdir -p $PREFIX
sudo make install

cd ../..

echo "*** To get rid of temporary files created during the build process,"
echo "*** you should enter the command:"
echo "***"
echo "***      rm -rf temp-gcc"

#rm -rf temp-gcc
