#!/usr/bin/make -f

export DEB_BUILD_MAINT_OPTIONS=hardening=+all,-pie,+fortify
DEB_HOST_ARCH ?= $(shell dpkg-architecture -qDEB_HOST_ARCH)
DEB_HOST_MULTIARCH ?= $(shell dpkg-architecture -qDEB_HOST_MULTIARCH)
DEB_HOST_ARCH_OS ?= $(shell dpkg-architecture -qDEB_HOST_ARCH_OS)

# SSE options
ifeq ($(DEB_HOST_ARCH),amd64)
CMAKE_ARCH_FLAGS = -DENABLE_SSE=ON -DENABLE_SSE2=ON -DENABLE_SSE3=OFF 
else
CMAKE_ARCH_FLAGS = -DENABLE_SSE=OFF -DENABLE_SSE2=OFF -DENABLE_SSE3=OFF 
endif

# No GL on armhf
ifneq ($(DEB_HOST_ARCH),armhf)
CMAKE_ARCH_FLAGS += -DWITH_OPENGL=ON
else
CMAKE_ARCH_FLAGS += -DWITH_OPENGL=OFF
endif

# TBB support
ifneq (,$(findstring $(DEB_HOST_ARCH), i386 amd64 ia64 powerpc ppc64))
CMAKE_ARCH_FLAGS += -DWITH_TBB=ON
else
CMAKE_ARCH_FLAGS += -DWITH_TBB=OFF
endif

# Linux-specific stuff
ifeq ($(DEB_HOST_ARCH_OS),linux)
CMAKE_ARCH_FLAGS += -DWITH_1394=ON -DWITH_V4L=ON
else
CMAKE_ARCH_FLAGS += -DWITH_1394=OFF -DWITH_V4L=OFF
endif

# For Java
export JAVA_HOME=/usr/lib/jvm/default-java

CMAKE_FLAGS = \
	-DCMAKE_INSTALL_PREFIX=/usr \
	-DCMAKE_INSTALL_LIBDIR="lib/$(DEB_HOST_MULTIARCH)" \
	-DCMAKE_VERBOSE_MAKEFILE=ON \
	-DCMAKE_C_FLAGS_RELEASE="$(CFLAGS)" \
	-DCMAKE_CXX_FLAGS_RELEASE="$(CXXFLAGS)" \
	-DCMAKE_SHARED_LINKER_FLAGS_RELEASE="$(LDFLAGS)" \
	-DCMAKE_EXE_LINKER_FLAGS_RELEASE="$(LDFLAGS)" \
	-DCMAKE_BUILD_TYPE=Release	\
	-DBUILD_EXAMPLES=ON	\
	-DINSTALL_C_EXAMPLES=ON	\
	-DINSTALL_PYTHON_EXAMPLES=ON	\
	-DBUILD_NEW_PYTHON_SUPPORT=ON	\
	-DWITH_FFMPEG=ON	\
	-DWITH_GSTREAMER=OFF	\
	-DWITH_GTK=ON	\
	-DWITH_JASPER=ON	\
	-DWITH_JPEG=ON	\
	-DWITH_PNG=ON	\
	-DWITH_TIFF=ON	\
	-DWITH_OPENEXR=ON \
	-DWITH_PVAPI=ON	\
	-DWITH_UNICAP=OFF	\
	-DWITH_EIGEN=ON \
	-DWITH_XINE=OFF	\
	-DBUILD_TESTS=OFF \
	-DCMAKE_SKIP_RPATH=ON \
	-DWITH_CUDA=OFF \
	$(CMAKE_ARCH_FLAGS)
# -DOPENCL_INCLUDE_DIR:PATH="/usr/include/CL/"

%:
	dh $@ --buildsystem=cmake --with python2 --with javahelper

override_dh_clean:
	rm -rf modules/python/src2/hdr_parser.pyc
	rm -rf modules/java/generator/rst_parser.pyc
	rm -rf modules/refman.rst

	dh_clean -O--buildsystem=cmake

override_dh_auto_configure:
	dh_auto_configure -- $(CMAKE_FLAGS)

override_dh_install:
	-rm --verbose -rf debian/tmp/usr/share/opencv/samples/octave
	-rm --verbose -rf debian/tmp/usr/share/opencv/samples/c/cvsample.dsp
	-rm --verbose -rf debian/tmp/usr/share/OpenCV/doc/license.txt

	# change install path of java library
	sed -i -e "s@share\/OpenCV\/java\/@lib\/jni\/@g" \
		debian/tmp/usr/share/OpenCV/OpenCVModules-release.cmake

	for f in $$(ls obj-*/lib/libopencv_*_s.a); do \
		cp --verbose --preserve=mode $$f debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)/$$(basename $$f _s.a).a; done
	dh_install -O--buildsystem=cmake --list-missing

override_dh_fixperms-indep:
	dh_fixperms
	chmod 644 $(CURDIR)/debian/opencv-doc/usr/share/doc/opencv-doc/examples/python/*.py
	chmod 644 $(CURDIR)/debian/opencv-doc/usr/share/doc/opencv-doc/examples/python2/*.py
