#!/bin/bash

set -e

# Try to find the legacy gccs
#if which gcc34 > /dev/null ; then
#export CC=gcc34
#elif which gcc32 > /dev/null ; then
#export CC=gcc32
#elif which gcc > /dev/null ; then
#export CC=gcc
#fi

# Update this for where you want to install
export INSTALL_PATH=/usr/local/gccn64

# We need to build things with the stuff we install
export PATH=$PATH:$INSTALL_PATH/bin

# Seem to be usable versions
BINUTILS_VER=2.16
GCC_VER=3.3.6
NEWLIB_VER=1.14.0

# Download and extract binutils
if [ ! -e binutils-$BINUTILS_VER ] ; then
if [ ! -e binutils-$BINUTILS_VER.tar.bz2 ] ; then
wget -c "http://ftp.gnu.org/gnu/binutils/binutils-$BINUTILS_VER.tar.bz2"
fi
echo "extracting binutils"
tar xjf binutils-$BINUTILS_VER.tar.bz2
fi

# Download and extract gcc
if [ ! -e gcc-$GCC_VER ] ; then
    GCC_FILENAME=gcc-$GCC_VER.tar.bz2
    if [ ! -e $GCC_FILENAME ] ; then
        GCC_FILENAME=gcc-core-$GCC_VER.tar.bz2
        if [ ! -e $GCC_FILENAME ] ; then
            wget -c "http://ftp.gnu.org/gnu/gcc/gcc-$GCC_VER/gcc-core-$GCC_VER.tar.bz2"
        fi
    fi
    echo "extracting gcc"
    tar xjf $GCC_FILENAME
fi

# Download and extract newlib
if [ ! -e newlib-$NEWLIB_VER ] ; then
if [ ! -e newlib-$NEWLIB_VER.tar.gz ] ; then
wget -c "ftp://sources.redhat.com/pub/newlib/newlib-$NEWLIB_VER.tar.gz"
fi
echo "extracting newlib"
tar xzf newlib-$NEWLIB_VER.tar.gz
fi

# Build binutils
if [ ! -e build-binutils ] ; then
mkdir build-binutils ; cd build-binutils
touch build-binutils-failed
../binutils-$BINUTILS_VER/configure --prefix=${INSTALL_PATH} --target=mips64 --with-cpu=mips64vr4300
make all
# try to install
make install || sudo make install || su -c "make install"
rm build-binutils-failed
cd ..
else
    if [ -e build-binutils/build-binutils-failed ] ; then
        echo "previous build of binutils did not succeed, remove build-binutils to try again"
        exit 1
    fi
fi

# Build gcc
if [ ! -e build-gcc ] ; then
mkdir build-gcc ; cd build-gcc
touch build-gcc-failed
../gcc-$GCC_VER/configure --prefix=${INSTALL_PATH} --target=mips64 --with-cpu=mip64vr4300 -enable-languages=c --disable-threads --with-newlib
make all-gcc 
make install-gcc || sudo make install-gcc || su -c "make install-gcc"
rm build-gcc-failed
cd ..
else
    if [ -e build-gcc/build-gcc-failed ] ; then
        echo "previous build of gcc did not succeed, remove build-gcc to try again"
        exit 1
    fi
fi

# Build newlib
if [ ! -e build-newlib ] ; then
mkdir build-newlib ; cd build-newlib
touch build-newlib-failed
../newlib-$NEWLIB_VER/configure --prefix=${INSTALL_PATH} --target=mips64 --with-cpu=mips64vr4300 --disable-multilib --disable-threads
make all
make install || sudo make install || su -c "make install"
rm build-newlib-failed
cd ..
else
    if [ -e build-newlib/build-newlib-failed ] ; then
        echo "previous build of newlib did not succeed, remove build-newlib to try again"
        exit 1
    fi
fi

# Build chksum64
gcc chksum64.c -o chksum64
