if [ -z "$SAGE_LOCAL" ]; then
    echo >&2 "SAGE_LOCAL undefined ... exiting"
    echo >&2 "Maybe run 'sage --sh'?"
    exit 1
fi

# This spkg shouldn't be installed if gcc is already installed
if [ -a "$SAGE_LOCAL"/bin/gcc ]; then
    echo >&2 "Error: gcc is already installed"
    exit 1
fi

# Exit on error
set -e

# Build in a separate directory, not in src/ (a.k.a. a VPATH build).
# This is the recommended way to build GCC.
mkdir gcc-build
cd gcc-build


# On OSX:
if [ "$UNAME" = "Darwin" ]; then
    # isl/cloog libraries are almost certainly from Homebrew and won't work
    GCC_CONFIGURE="--without-isl --without-cloog $GCC_CONFIGURE"

    # Use 'bootstrap-debug' build configuration to force stripping of object
    # files prior to comparison during bootstrap (broken by Xcode 6.3).
    # See #18156
    GCC_CONFIGURE="--with-build-config=bootstrap-debug $GCC_CONFIGURE"
fi

# Let Gfortran build on Raspberry Pi using hard floats.
if [ `uname -m` = "armv6l" ]; then
    GCC_CONFIGURE="--with-arch=armv6 --with-fpu=vfp --with-float=hard $GCC_CONFIGURE"
fi

# Let Gfortran build on more recent ARM boards using hard floats.
if [ `uname -m` = "armv7l" ]; then
    GCC_CONFIGURE="--with-arch=armv7-a --with-fpu=vfpv3-d16 --with-float=hard $GCC_CONFIGURE"
fi

if [ "$SAGE_CHECK" = yes ]; then
    # Enable internal checks in GCC.  These checks do not affect the
    # binaries produced by GCC, but they do increase the compile time
    # of everything compiled with GCC.
    GCC_CONFIGURE="$GCC_CONFIGURE --enable-checking=yes"
fi

# Use the assembler/linker specified by $AS/$LD if they differ from the
# default.
if [ -n "$AS" -a "$AS" != "as" ]; then
    CONFIGURE_AS="--with-as=$AS"
fi
if [ -n "$LD" -a "$LD" != "ld" ]; then
    CONFIGURE_LD="--with-ld=$LD"
fi

../src/configure \
    --prefix="$SAGE_LOCAL" \
    --with-local-prefix="$SAGE_LOCAL" \
    --with-gmp="$SAGE_LOCAL" --with-mpfr="$SAGE_LOCAL" --with-mpc="$SAGE_LOCAL" \
    --with-system-zlib \
    --disable-multilib \
    --disable-nls \
    --enable-languages=fortran \
    --disable-bootstrap \
    --disable-libitm \
    $GCC_CONFIGURE "$CONFIGURE_AS" "$CONFIGURE_LD"

sdh_make BOOT_LDFLAGS="-Wl,-rpath,$SAGE_LOCAL/lib"

sdh_make_install

# The spkg still installs a minimal C compiler that needs to be removed
# so it doesn't conflict with the configured C compiler.
rm "$SAGE_DESTDIR_LOCAL"/bin/gcc "$SAGE_DESTDIR_LOCAL"/bin/cpp
