#!/bin/bash
#
export PATH=/opt/local/bin:$PATH:/opt//local/Library/Frameworks/wxWidgets.framework/Versions/wxWidgets/3.0/bin
#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="--disable-debug-checks"
	fi

	CXX="`wx-config --cxx` " \
	CFLAGS="$CFLAGS -I/opt/local/include -I/usr/local/include " \
	CXXFLAGS="$CXXFLAGS -I/opt/local/include -I/usr/local/include " \
	LDFLAGS="$LDFLAGS -L/opt/local/lib -L/usr/local/lib" \
	./configure $SHOULD_PARALLEL $DISABLE_DEBUG --enable-mgl2=yes

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


	make clean
fi

make -j8

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

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


#Update gettext translation
#----
echo "Updating translation files..."
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

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

