#!/bin/bash
# Script to build host tool chain. Tools are built in the "build" directory,
# Built tools are installed in the "/opt/BRECIS/<host>" directory - specifically
# in /opt/BRECIS/<host>/bin where <host> represents the output from
# config.guess

exec 2>&1

# Find source trees for binutils and gcc.
tars=${archives:-.}
source ./find-src binutils gcc

hosttype=`./${binutils}/config.guess`
prefix=${dest:-/opt/BRECIS}/${hosttype}

rm -f host*.out
mkdir -p ${prefix} ${prefix}/bin ${prefix}/include ${prefix}/lib || exit 1
mkdir -p ${prefix}/${target}

export	PATH=${prefix}/bin:$PATH

if [ "x`uname`" = "xDarwin" ]; then
	echo Building on Darwin
	hostcc="CC=cc -no-cpp-precomp -O2"
	cc4target="CC_FOR_TARGET=cc -no-cpp-precomp -O2"
	bintarg="--target=powerpc-elf --host=powerpc-netbsdelf"
else
	hostcc="XFOO="
	cc4target="XFOO="
	bintarg=
fi

rm -rf host-binutils host-gcc
mkdir -p host-binutils host-gcc

cd host-binutils
rm -f hostconf-fail hostmake-fail hostinst-fail

# Configure host binutils
if ! ../$binutils/configure --prefix=${prefix} ${bintarg}
then
	touch hostconf-fail
fi | tee ../hostconfbin.out
if [ -f hostconf-fail ]; then
	echo +=+=+= host binutils not configured +=+=+=
	rm -f hostconf-fail
	exit 1
fi
echo +=+=+= host binutils configured +=+=+=

# Make host binutils
if ! make "${hostcc}" "${cc4target}" ; then
	touch hostmake-fail
fi | tee ../hostmakebin.out
if [ -f hostmake-fail ]; then
	echo +=+=+= host binutils NOT made +=+=+=
	rm -f hostmake-fail
	exit 1
fi
echo +=+=+= host binutils make +=+=+=

# Install host binutils
if ! make "${hostcc}" "${cc4target}" install ; then
	touch hostinst-fail
fi | tee ../hostinstbin.out
if [ -f hostinst-fail ]; then
	echo +=+=+= host binutils NOT installed +=+=+=
	rm -f hostinst-fail
	exit 1
fi
echo +=+=+= host binutils installed +=+=+=

cd ../host-gcc
rm -f hostconf-fail hostmake-fail hostinst-fail

# Configure host gcc
if ! ../$gcc/configure --prefix=$prefix --enable-languages=c
then
	touch hostconf-fail
fi | tee ../hostconfgcc.out
if [ -f hostconf-fail ]; then
	echo +=+=+= host gcc NOT configured +=+=+=
	rm -f hostconf-fail
	exit 1
fi
echo +=+=+= host gcc configured +=+=+=

# Make host gcc
if ! make "${hostcc}" "${cc4target}" bootstrap ; then
	touch hostmake-fail
fi | tee ../hostmakegcc.out
if [ -f hostmake-fail ]; then
	echo +=+=+= host gcc NOT made +=+=+=
	rm -f hostmake-fail
	exit 1
fi
echo +=+=+= host gcc make +=+=+=

# Install host gcc
if ! make "${hostcc}" "${cc4target}" install ; then
	touch hostinst-fail
fi | tee ../hostinstgcc.out
if [ -f hostinst-fail ]; then
	echo +=+=+= host gcc NOT installed +=+=+=
	rm -f hostinst-fail
	exit 1
fi
echo +=+=+= host gcc installed +=+=+=

cd ..

echo Host tool build complete
