#!/bin/bash
#
export PATH=/opt/local/bin:$PATH
#This will make the mac .app bundle

if [ $1 = '--update-config=yes' ]; then
	echo "Updating configuration files"

	if [ $2 = '--parallel=yes' ]; then
		echo "Building parallel"
		SHOULD_PARALLEL="--enable-openmp-parallel"
	fi

	if [ $3 = '--debug=no' ]; then
		echo "Building debug off"
		DISABLE_DEBUG="--enable-no-debug-checks"
	fi

	./configure $SHOULD_PARALLEL $DISABLE_DEBUG \
		--with-mgl-libs="-L/opt/local/lib -lmgl" \
		--with-mgl-flags="-I/opt/local/include" \
		--with-freetype=/opt/local \
		--with-gsl-flags=-I`gsl-config --prefix`/include \
		--with-gsl-libs="-L`gsl-config --prefix`/lib -lgsl" \
		--with-wx-prefix=`wx-config --prefix` \
		--with-xml-config=`which xml2-config` \
		--with-libpng-flags=-I`libpng14-config --prefix`/include \
		--with-libpng-link="-L`libpng14-config --prefix`/lib -lpng14" \
		--with-intl-libs="-L/opt/local/lib -lintl " \
		LDFLAGS="-headerpad_max_install_names" \
#		--build=x86_64-apple-darwin11.0.0


	if [ $? -ne 0 ]; then
		echo "Configure unsuccessful - exiting"
		exit
	fi


	make clean
fi

make -j8

if [ $? -ne 0 ]; then
	echo "Make unsuccessful - exiting"
	exit
fi

echo "Updating .app bundle..."
mkdir -p ./3Depict.app/Contents/MacOS/
mkdir -p ./3Depict.app/Contents/Resources/
mkdir -p ./3Depict.app/Contents/libs/
cp ./src/3Depict ./3Depict.app/Contents/MacOS/3Depict
cp src/tex-source/3Depict-icon.icns ./3Depict.app/Contents/Resources/3Depict-icon.icns
touch ./3Depict.app/Contents/PkgInfo
touch ./3Depict.app/Contents/info.plist
#copy textures
cp -R ./src/textures ./3Depict.app/Contents/Resources


#Update gettext translation
#----
echo "Updating translation files..."
#cp -Rp locales/* ./3Depict.app/Contents/Resources/
for i in `ls ./translations/3Depict_*.mo`
do
	j=`echo $i | sed 's/.\/translations\/3Depict_//' | sed 's/.mo//'`
	mkdir -p ./3Depict.app/Contents/Resources/$j/LC_MESSAGES/
	cp $i ./3Depict.app/Contents/Resources/$j/LC_MESSAGES/3Depict.mo
	echo "$i $j"
done

#----


# relabel libraries for packaging
if [ x`which dylibbundler` == x"" ] ; then
	echo "dyllibbundler command does not appear to be available. Package built, but cannot relabel libaries to use in-package versions"
	exit 1
fi

/opt/local/bin/dylibbundler -od -b -x ./3Depict.app/Contents/MacOS/3Depict -d  ./3Depict.app/Contents/libs
echo "Done"

