#!/bin/sh

NAME="[ogre]"
WORKING_DIR="ogre/ogre_src_v1-8-1"
#WORKING_DIR="ogre/ogre-1-9-0-sinbad-ogre-dd30349ea667"

BUILD_DIR=build

source ./build_common.sh

if [ $DO_CLEAN -eq 1 ]
then
	rm -rf $BUILD_DIR
	check_result $? "cleaning build dir"
fi

if [ $DO_BUILD -eq 1 ]
then
	# modify sources to make it work with mingw64
	sed -i "s/ -march=i686//" "CMakeLists.txt"
	check_result $? "remove compiler flag -march=i686"
	sed -i "s/DxErr/dxerr9/" "CMake/Packages/FindDirectX.cmake"
	check_result $? "renaming DxErr library in FindDirectX.cmake"
	sed -i "s/#define __uuidof(Object) IID_##Object//" "OgreMain/include/WIN32/OgreMinGWSupport.h"
	check_result $? "removing re-definition of __uuidof from OgreMinGWSupport.h"
	sed -i "s/intptr_t __security_cookie;//" "OgreMain/src/WIN32/OgreMinGWSupport.cpp"
	check_result $? "removing re-definition of __security_cookie from OgreMinGWSupport.cpp"
	sed -i "s/(intptr_t/(uintptr_t/g" "OgreMain/src/WIN32/OgreMinGWSupport.cpp"
	check_result $? "replacing intptr_t with uintptr_t in OgreMinGWSupport.cpp"
	sed -i "s/(intptr_t/(uintptr_t/g" "RenderSystems/Direct3D9/src/OgreD3D9Plugin.cpp"
	check_result $? "replacing intptr_t with uintptr_t in OgreD3D9Plugin.cpp"
	sed -i "s/#include <DxErr.h>/#include <dxerr9.h>\n#define DXGetErrorDescription DXGetErrorDescription9/" "RenderSystems/Direct3D9/include/OgreD3D9Prerequisites.h"
	check_result $? "replacing include and add define in OgreD3D9Prerequisites.h"

	# prepare build directory
	mkdir -p $BUILD_DIR
	check_result $? "creating build dir"
	cd $BUILD_DIR

	# run cmake
	cmake -DCMAKE_BUILD_TYPE=Release \
		  -DOGRE_DEPENDENCIES_DIR=${TEMP_DIR}/ogredeps \
		  -DBOOST_LIBRARYDIR=${TARGET_BIN_DIR} \
		  -DBOOST_INCLUDEDIR=${TARGET_INC_DIR}/boost \
		  -DOGRE_BUILD_RENDERSYSTEM_D3D11=OFF \
		  .. -G "MSYS Makefiles"

	check_result $? "cmake"

	# compile
	make -j8 install
	check_result $? "make install"

	# copy libraries into target directory
	find "sdk/bin/release" -name "Ogre*.dll" -exec cp -a {} ${TARGET_BIN_DIR} \;
	check_result $? "copying Ogre-libraries"
	find "sdk/bin/release" -name "Plugin_*.dll" -exec cp -a {} ${TARGET_BIN_DIR} \;
	check_result $? "copying Plugin-libraries"
	find "sdk/bin/release" -name "RenderSystem_*.dll" -exec cp -a {} ${TARGET_BIN_DIR} \;
	check_result $? "copying RenderSystem_-libraries"

	# copy includes
	mkdir -p ${TARGET_INC_DIR}/ogre
	check_result $? "creating include dir"
	cp -aT "sdk/include/OGRE" ${TARGET_INC_DIR}/ogre/include
	check_result $? "copying includes"

	echo "${NAME} Finished building ${NAME}"
fi
