#!/bin/bash
#
# Copyright(c) Mauro Carvalho Chehab <m.chehab@samsung.com>
#
# License: GPLv2


# Requires the following packages:
#	gcc, gcc-c++, make, texinfo

#
# Configuration
#
GNU_REPO=http://gnu.c3sl.ufpr.br/ftp
PREFIX=/usr/local/cross/$ARCH
BINUTILS_VER=2.22
GCC_VER=4.8.1
GMP_VER=5.0.5
MPFR_VER=2.4.2
MPC_VER=1.0.1

#
# Functions
#

run ()
{
	echo -n "`pwd`$ "
	echo $@
	$@
	if [ "$?" != "0" ]; then
		exit -1
	fi
}

check_get_sources()
{
	if [ "$4" == "" ]; then
		fname=$1-$3.tar.bz2
	else
		fname=$1-$3.tar.$4
	fi

	if [ -s "$fname" ]; then
		return
	fi

	echo downloading $GNU_REPO/$1/$2/$fname
	run wget -O $fname $GNU_REPO/$1/$2/$fname
}

extract_sources()
{
	if [ "$4" != "" ]; then
		dirname=$4/$1-$2
	else
		dirname=$1-$2
	fi


	if [ -d "$dirname" ]; then
		return
	fi

	if [ "$3" == "gz" ]; then
		fname=$1-$2.tar.gz
		COMPRESS="z"
	else
		fname=$1-$2.tar.bz2
		COMPRESS="j"
	fi

	if [ "$4" == "" ]; then
		tar xvf$COMPRESS $fname
	else
		echo tar xvf$COMPRESS $fname --directory=$4/
		tar xf$COMPRESS $fname --directory=$4/
		ln -sf $1-$2 $4/$1
	fi
}

#
# Main
#

if [ "$1" == "" ]; then
	echo "$0 <arch>"
	exit -1
else
	#ARCH=powerpc-linux
	ARCH=$1
fi

BINUTILS=binutils-$BINUTILS_VER
GCC=gcc-$GCC_VER

#
# Download source codes
#
check_get_sources gcc gcc-$GCC_VER $GCC_VER
check_get_sources binutils "" $BINUTILS_VER
check_get_sources gmp "" $GMP_VER
check_get_sources mpfr "" $MPFR_VER
check_get_sources mpc "" $MPC_VER gz

#
# Extract source codes
#
extract_sources binutils $BINUTILS_VER bz2
extract_sources gcc $GCC_VER bz2
extract_sources gmp $GMP_VER bz2 $GCC
extract_sources mpfr $MPFR_VER bz2 $GCC
extract_sources mpc $MPC_VER gz $GCC

#
# Compile binutils
#
rm -rf binutils-build
run mkdir -v binutils-build
run cd binutils-build
run ../$BINUTILS/configure --target=$ARCH --prefix=$PREFIX --disable-nls
run make all
run sudo make install
run cd ..

#
# Compile gcc
#
rm -rf gcc-build
run mkdir -v gcc-build
run cd gcc-build
run ../$GCC/configure
	--enable-languages=c --target=$ARCH --prefix=$PREFIX \
	--disable-nls --disable-shared --disable-multilib --disable-decimal-float --disable-threads \
	--disable-libmudflap --disable-libssp --disable-libgomp --disable-libquadmath --disable-target-libiberty \
	--disable-target-zlib \
	--disable-libatomic--disable-libitm --disable-libmudflap --disable-libsanitizer --disable-libssp \
	--without-ppl --without-cloog \
	--with-mpfr-include=$(pwd)/../$GCC_VER/mpfr/src --with-mpfr-lib=$(pwd)/mpfr/.libs

run make all
run sudo make install