#!/usr/bin/env bash

# Major thanks to Mark Dayel for his post at
# http://www.dayel.com/2009/09/building-gsl-universal-binary/
# upon which this script is almost entirely based.
# I only added an install to the standard location (which is
# why sudo is required), gave slightly more unique names to a
# couple of directories that are now temporary, and cleaned
# up by removing a few unnecessary files and directories
# when the install is finished.

# invoke sudo right away, so we have permission when we need it
sudo echo

# possible archs: i386 ppc x86_64 ppc64
# note: ppc64 doesn't work in Snow Leopard
ARCHITECTURES="i386 x86_64"

# number of cpus to use during compile
COMPILETHREADS=2

COMPILER=gcc
#COMPILER=/Developer/usr/bin/llvm-g++-4.2

# configure flags
CONFFLAGS="--disable-shared"

# compiler flags
COMPFLAGS="-O3"

# find the name of the source file
SOURCEFILE=`find . -name "gsl*.tar.gz" -depth 1`
SOURCEFILE=${SOURCEFILE:2:100}
GSLVER=${SOURCEFILE%.tar.gz}

# unzip the main source file
tar -xzf $SOURCEFILE

for ARCH in $ARCHITECTURES
do
	echo Compiling for ${ARCH}...

	# copy source to new directory
	cp -r ${GSLVER} ${GSLVER}_$ARCH
	cd ${GSLVER}_$ARCH

	# configure for architecture
	if [ "$ARCH" != "ppc64" ] ; then	# not sure why we have to do cross compile for ppc64 but not ppc...
		env CC="$COMPILER" CFLAGS="-arch $ARCH $COMPFLAGS" LDFLAGS="-arch $ARCH" ./configure $CONFFLAGS --build=$ARCH
	else
		env CC="$COMPILER" CFLAGS="-arch $ARCH $COMPFLAGS" LDFLAGS="-arch $ARCH" ./configure $CONFFLAGS --host=$ARCH
	fi

	# compile for architecture
	make clean ; nice make -j $COMPILETHREADS

	cd ..
done

mkdir gsl_include
mkdir gsl_libs
cp `find ${GSLVER} -name "*.h"` gsl_include

echo
echo
echo Making Universal Binaries...

find ${GSLVER}_$ARCH -name "*.a"

for LIBRARY in `find ${GSLVER}_$ARCH -name "*.a"`
do
	echo
	LIB=`basename $LIBRARY`
	echo Library: $LIB
	find . -name $LIB
	lipo -create `find . -name $LIB | xargs` -output gsl_libs/$LIB
	lipo -info gsl_libs/$LIB
done

echo
echo Universal Binaries:
echo
lipo -info gsl_libs/*.a

echo
echo Installing headers and libs...
echo
sudo mkdir -p /usr/local/include
sudo mkdir -p /usr/local/lib
sudo mv gsl_include /usr/local/include/gsl
sudo mv gsl_libs/* /usr/local/lib/

echo
echo Cleaning up...
echo
rmdir gsl_libs
rm -R ${GSLVER}
