#!/bin/bash
#

#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 --with-freetype=/usr/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 -lintlcopy " \
		$SHOULD_PARALLEL \
		$DISABLE_DEBUG \
		LDFLAGS=" -headerpad_max_install_names"

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


	make clean
fi

make -j2

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

echo "Updating .app bundle..."
mkdir -p ./3Depict.app/Contents/MacOS/
cp ./src/3Depict ./3Depict.app/Contents/MacOS/3Depict
cp src/tex-source/3Depict-icon.icns ./3Depict.app/Contents/Resources/wxmac.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/

#----


# 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

dylibbundler -od -b -x ./3Depict.app/Contents/MacOS/3Depict -d ./3Depict.app/Contents/libs -i /usr/lib
install_name_tool -change /opt/local/lib/libfreetype.6.dylib @executable_path/../libs/libfreetype.6.dylib ./3Depict.app/Contents/libs/libftgl.2.1.3.dylib

echo "Done"

