#! /bin/bash
# bash is necessary to use lib{iberty,gomp} syntax; dash doesn't have this.

# Install a newly built gcc from its build directory
# without affecting the main system compiler.
#
# Run this script from inside a directory called gcc-X.Y.Z-build
# where X.Y.Z is your
# full gcc version number.
#
#    Martin Guy <martinwguy@yahoo.it>, November 2008

set -e		# Exit if anything fails unexpectedly

vendor=crunch
lname=armv4tl-$vendor-linux-gnueabi
lver=$(basename `/bin/pwd` | sed -n '/gcc-\([0-9]\.[0-9]\.[0-9]\)-build/s//\1/p')
case $lver in
4.1.?) suffix=4.1-$vendor ;;
4.2.?) suffix=4.2-$vendor ;;
4.3.?) suffix=4.3-$vendor ;;
4.4.?) suffix=4.4-$vendor ;;
*)	echo "Failed to extract version number from current directory name."
	exit 1 ;;
esac

rm -rf /usr/local/lib{,exec}/gcc/$lname/$lver

# Make symlinks so that it finds standard include and lib files
test -d /usr/local/$lname || mkdir /usr/local/$lname
rm -f /usr/local/$lname/{include,lib}
ln -s /usr/include/arm-linux-gnueabi /usr/local/$lname/include
ln -s /usr/lib/arm-linux-gnueabi /usr/local/$lname/lib

make CFLAGS_FOR_TARGET="-mcpu=ep9312 -mfpu=maverick -mfloat-abi=softfp" install || {
	echo "'make install' failed."
	exit 1
}

# Make the GCC libraries local to this one version, otherwise their presence in
# /usr/local/lib overrides the system compiler's ones.
mv /usr/local/lib/lib{gcc,gomp,iberty,mudflap}* /usr/local/lib/gcc/$lname/$lver/

# Reduce size of binaries for packaged version
strip /usr/local/bin/{gcc,cpp}-$suffix \
	/usr/local/libexec/gcc/$lname/$lver/{cc1,collect2}

# Remove junk and long-named versions of compiler.
rm -f /usr/local/bin/$lname-gcc-$lver
rm -f /usr/local/bin/{$lname-gcc,gccbug,gcov}-$suffix
rm -rf /usr/local/lib/gcc/$lname/$lver/install-tools
rmdir /usr/local/lib/gcc/$lname/$lver/finclude || : no problem	# empty fortran header dir

case "$lver" in
4.3.*)	# 4.3 doesn't work unless it has some fixed headers. By default it fixes
	# just about everything that happened to be on the build system.
	# Here we just leave what Debian gcc-4.3 has.
	(
	 cd /usr/local/lib/gcc/$lname/$lver/include-fixed
	 find *	-maxdepth 0 \
		! -path README		\
		! -path limits.h	\
		! -path syslimits.h	\
		! -path linux		\
		-exec rm -r {} \;
	)
	;;
*)	# 4.1 and 4.2 don't seem to have this
	;;
esac

# Leave gcc-4.X-crunch manual page because option flags have changed.
rm -f /usr/local/man/man1/{cpp,gcov}-$suffix.1
rm -f /usr/local/info/{cpp,cppinternals,gcc,gccinstall,gccint,libgomp}.info

# Fix ownership of files
find /usr/local/lib/gcc/$lname/ -print0 | xargs -0 chown root:root

echo Now you probably want to run tarball gcc-$suffix
