#!/usr/bin/make -f
# -*- makefile -*-

# get Octave paths
include /usr/share/octave/debian/defs.make
# get Matlab paths
include /usr/share/matlab/debian/defs.make

srcpkg = $(shell LC_ALL=C dpkg-parsechangelog | grep '^Source:' | cut -d ' ' -f 2,2)
debver = $(shell LC_ALL=C dpkg-parsechangelog | grep '^Version:' | cut -d ' ' -f 2,2 )
uver = $(shell echo $(debver) | sed -e 's,-[^-]*$$,,g' )
uver_nondfsg = $(shell echo $(uver) | sed -e 's,.dfsg[0-9]*,,g')

# Directories which are created/populated/cleanedup
BDIRS=Psychtoolbox/PsychBasic/Octave3LinuxFiles Psychtoolbox/PsychBasic/PsychPlugins \
 Psychtoolbox/PsychBasic/Octave4LinuxFiles64 Psychtoolbox/PsychBasic/Octave4LinuxFiles
OCT_SHAREDDIR=debian/psychtoolbox-3-common/usr/share/psychtoolbox-3
OCT_LIBDIR=debian/octave-psychtoolbox-3/usr/lib/psychtoolbox-3

export LDFLAGS=-Wl,--as-needed

# Critical for building on machines with multiarch support
# (e.g. ubuntu 11.04)
GLIB_INCLUDES=$(shell pkg-config --cflags glib-2.0)
GST_INCLUDES=$(shell pkg-config --cflags gstreamer-1.0)
GLEW_VERSION=$(shell pkg-config --modversion glew)

# Upstream advises to build without optimization at the moment
export CXXFLAGS=-Wall -g -O0
export CFLAGS=-Wall -g -O0 -std=gnu99 $(GLIB_INCLUDES) $(GST_INCLUDES)

# Let's use "advanced" bash patterns
export SHELL=/bin/bash

%:
	dh $@ --with quilt --buildsystem=makefile

override_dh_quilt_patch:
	dpkg --compare-versions $(GLEW_VERSION) lt 999.1.11.0 \
	 || { echo "I: system GLEW is $(GLEW_VERSION). Thus adding a use_system_GLEW patch"; \
		  echo 'deb_use_system_GLEW' >> debian/patches/series; \
	      echo "I: moving copy of glew.c aside"; \
	      find -iname glew.c | while read f; do mv $$f $${f}__; done; }
	dh_quilt_patch

override_dh_quilt_unpatch:
	dh_quilt_unpatch
	dpkg --compare-versions $(GLEW_VERSION) lt 1.11.0 \
	 || { find -iname glew.c__ | while read f; do mv $$f $${f//__/}; done; \
	      sed -i -e '/deb_use_system_GLEW/d' debian/patches/series; }

# 10 - PsychCV
# 12 - PsychOculusVRCore.mex  -- oculus VR stuff
# 13 - ARM only for RPi, needs libwiringpi-dev
override_dh_auto_build: build-stamp
build-stamp:
	mkdir -p $(BDIRS)

	: # Build all extensions, but:
	: #  4  libeyelink -- non-distributable binary blob with open-sourced API
	cd PsychSourceGL/Source/; \
		for mode in 0 1 2 3   5 6 7 8 9  11  14 15; do \
		  octave -p $(CURDIR)/Psychtoolbox/PsychOneliners -q --eval "linuxmakeitoctave3($$mode)" || exit 1; \
	done

	: # Manually build OpenGL text renderer extension
	cd PsychSourceGL/Cohorts/FTGLTextRenderer; \
	$(CXX) $(CXXFLAGS) -I. -I/usr/include/ -I/usr/include/freetype2/ \
		-L/usr/lib -pie -shared -fPIC \
		-Wl,-Bsymbolic -Wl,-Bsymbolic-functions \
		-Wl,--version-script=linuxexportlist.txt \
		-o libptbdrawtext_ftgl.so.1 \
		libptbdrawtext_ftgl.cpp qstringqcharemulation.cpp OGLFT.cpp \
		-lGL -lGLU -lfontconfig -lfreetype

	: # Manually build tcp_udp_ip toolbox's extension
	cd ./Psychtoolbox/PsychHardware/iViewXToolbox/tcp_udp_ip; \
		octave -q --eval "mex pnet.c"; [ -f pnet.mex ]

	install --mode=0644 PsychSourceGL/Cohorts/FTGLTextRenderer/libptbdrawtext_ftgl.so.1 \
	   Psychtoolbox/PsychBasic/PsychPlugins
	install -T --mode=0644 managementtools/WelcomeSplash-dfsg.ppm ./Psychtoolbox/PsychBasic/WelcomeSplash.ppm
	touch $@

override_dh_auto_test:
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	: # Smoke test some Demos and Tests -- some are excluded for various reasons
	: # image would be needed for one of the demos
	cd Psychtoolbox/PsychDemos/PsychTutorials/; ln -sf ../konijntjes1024x768*.jpg .
	cd Psychtoolbox/PsychTests/; ln -sf ../PsychDemos/konijntjes1024x768*.jpg .

	: # Run tests with fake HOME so ptb-3 could write its things
	mkdir -p tests-home; export HOME=$(CURDIR)/tests-home; \
	find Psychtoolbox/PsychDemos Psychtoolbox/PsychTests -type f -iname *.m \
	| grep -v -e "FAILURES DUE TO ABSENT FUNCTIONALITY IN TEST ENVIRONMENT" \
      -e Contents -e Stereo -e Serial -e PsychCV \
      -e Cedrus -e BitsPlus -e Kinect -e GPGPU -e DualHeads -e DaqTest \
      -e Matlab -e FitCumNormYNTest -e OSAUCSTest -e FitGammaPow -e FitGammaDemo \
      -e DirectInputMonitoringTest -e PosterBatchAnalyzeTimestamps \
	  -e OldNewReco -e AlphaImageDemo/[^A] \
      -e ClutAnimDemo -e MinimumMotionExp -e AdditiveBlendingForLinearSuperpositionTutorial \
      -e ImagingVideoCaptureDemo -e AudioTunnel3DDemo \
      -e DetectionRTInVideoDemo \
      -e VideoRecordingDemo -e PlayMoviesDemo -e PlayInterlacedMovieDemo \
      -e ErrorCatchDemo -e MovieDemo\.m -e VideoTextureExtractionDemo \
      -e VideoCapture \
      -e DatarecordingFromISCANDemo -e PsychRTBoxDemo \
      -e BlurredMipmapDemo \
      -e Tests.*Timing -e HIDIntervalTest \
      -e HighPrecisionLuminanceOutputDrivers -e HIDTest \
      -e SyncedCLUTUpdateTest -e GetSecsTest -e ConvolutionKernelTest \
      -e OSSchedulingAccuracyTest -e PTBAndVSETColorimetryTest \
      -e LoadGenerator \
    | grep -v -e "REQUIRE SOUND I/O (more in above list)" \
      -e Sound -e Audio -e BasicAMAndMixScheduleDemo -e SimpleVoiceTriggerDemo \
      -e KeyboardLatencyTest \
      -e LoadMovieIntoTexturesDemo -e PlayMoviesWithoutGapDemo2 \
    | grep -v -e "REQUIRE USER INPUT (more in the first list (TODO))" \
      -e RenderDemo -e CalDemo -e KbDemo -e KbQueueDemo \
    | grep -v -e "REQUIRE TOO LONG TO COMPLETE (and otherwise doesn't exit)" \
      -e QuestTest \
    | grep -v -e "KNOWN FAILURES TO BE FIXED (more in the first list (TODO))" \
      -e PlayMoviesWithoutGapDemo1 \
      -e FitWeibull.*Test -e DeinterlacerTest -e FitConeFundamentalsTest \
      -e AlphaMultiplicationTest -e MinExpEntStairDemo \
    | grep -v -e "REQUIRE SOME ADDITIONAL CMDLINE TOOLS AND SPECIAL HW" \
      -e PTBAndIsetbioColorimetryTest \
	| xargs debian/run_tests || echo "TESTS FAILED"

#      -e MovieDemos \
	: # Cleanup
	find -iname MLIexpSubj11.txt -delete
	find -type f -name core -delete
else
	: # Skip unittests due to nocheck
endif


override_dh_auto_install:
	dh_auto_install
	: # to guarantee -common existance for arch-dep builds only:
	mkdir -p $(OCT_SHAREDDIR)
	rsync -a --exclude=*.o ./Psychtoolbox/ $(OCT_SHAREDDIR)

	: # Move .mex to reside alongside with .m to gain easy help in octave
	mv $(OCT_SHAREDDIR)/PsychBasic/Octave3LinuxFiles/* $(OCT_SHAREDDIR)/PsychBasic
	: # But PsychHID must go into PsychHardware alongside with .m
	mv $(OCT_SHAREDDIR)/PsychBasic/PsychHID.mex $(OCT_SHAREDDIR)/PsychHardware
	rmdir $(OCT_SHAREDDIR)/PsychBasic/Octave3LinuxFiles

	: # Move .mex binaries under /usr/lib and create symlinks file to point back
	mkdir -p $(OCT_LIBDIR)
	cp debian/octave-psychtoolbox-3.links.in  debian/octave-psychtoolbox-3.links
	find $(OCT_SHAREDDIR)/ -iname \*.mex | while read f; do \
		fn=$$(basename $$f); ds=$$(dirname $$f); \
		dl=$$(echo $$ds | sed -e 's,psychtoolbox-3-common,octave-psychtoolbox-3,g' -e 's,/share/,/lib/,g'); \
		echo "I: Moving $$f under $$dl"; \
		mkdir -p $$dl; \
		mv $$f $$dl; \
		echo "/usr/lib$${f#*usr/share}	/usr$${f#*usr}" >> debian/octave-psychtoolbox-3.links; \
	done

	cp debian/psychtoolbox-3-lib.links.in  debian/psychtoolbox-3-lib.links
	find $(OCT_SHAREDDIR)/ -iname \*.so* -o -iname \*.a | while read f; do \
		fn=$$(basename $$f); ds=$$(dirname $$f); \
		dl=$$(echo $$ds | sed -e 's,psychtoolbox-3-common,psychtoolbox-3-lib,g' -e 's,/share/,/lib/,g'); \
		echo "I: Moving $$f under $$dl"; \
		mkdir -p $$dl; \
		mv $$f $$dl; \
		echo "/usr/lib$${f#*usr/share}	/usr$${f#*usr}" >> debian/psychtoolbox-3-lib.links; \
	done

	: # Filter out duplicate licenses etc
	find debian/ -iname 3Dlabs-License.txt -o \
				 -iname COPYING -o \
				 -iname *license.txt | xargs -r rm

	: # Filter out some scripts which aren't pertitent to Debian systems
	find debian/ -iname simplepsychtoolboxsetup.sh -o -iname setupdate.sh | xargs -r rm
	find debian/ -regextype posix-egrep -regex '.*/(Update|Setup|Download)Psychtoolbox\..*' -delete

	: # Remove unreproducible files
	find debian/ -name octave-workspace | xargs -r rm

override_dh_makeshlibs:
	dh_makeshlibs
	: # Provide Octave:Depends, do it in backports friendly way
	if hash dh_octave_substvar; then \
		dh_octave_substvar -poctave-psychtoolbox-3; \
	elif hash octave-depends; then \
		octave-depends; \
	else \
		echo 'octave:Depends=octave (>= 3.4.3-1~)' >> debian/octave-psychtoolbox-3.substvars; \
	fi

#override_dh_fixperms:
#	dh_fixperms

override_dh_strip:
	dh_strip --dbg-package=psychtoolbox-3-dbg

override_dh_shlibdeps:
	@: # octave will take care of proper deps for extensions -- no need to scan
	@: # them and warn all the time
	dh_shlibdeps -l$(shell octave-config --print OCTLIBDIR)

	: # Manually remove executable bit for everything not to be executed (e.g. .mex .m .so.*)
	@: # needs to be done post dh_strip,dh_shlibdeps so that .mex are found by dh_strip, dh_shlibdeps
#	find debian/ -regextype posix-egrep \
#	-regex '.*\.(c|jpg|vert|frag|xml|html|hiro|kanji|mat|m|txt|mex|so(|\..*))' \
#	-perm /+x -print0 \
	@: # strip from all files since we do not have any real executable there
	find debian/ -ipath '*psych*/usr/*' -perm /+x -type f ! -iname ATIRadeonperf_Linux -print0 \
	| xargs -0 --no-run-if-empty chmod a-x

override_dh_installchangelogs:
	dh_installchangelogs debian/changelog.upstream

override_dh_clean:
	$(MAKE) -C PsychSourceGL/Cohorts/PortAudio clean || :
	dh_clean
	rm -f ./Psychtoolbox/PsychBasic/WelcomeSplash.ppm
	rm -rf build-stamp build
	: # Manually remove  additional trash
	find Psych* -regextype posix-egrep -regex '.*\.(o|mex|so(|\..*))' -delete
	-rmdir $(BDIRS)
	: # Prune some Debian generated files
	rm -f debian/octave-psychtoolbox-3.links debian/psychtoolbox-3-lib.links

debian/changelog.upstream:
	git log --merges remotes/origin/beta >| $@

get-orig-source: debian/changelog.upstream
	@echo "I: Exporting free portion of `git describe dfsg`"; \
	git archive --format=tar --prefix=$(srcpkg)-$(uver)/ dfsg | \
        gzip -9 > $(srcpkg)_$(uver).orig.tar.gz

# Fetch all those binary blobs to go into non-free binaries packages
get-orig-source-nonfree:
	@beta_merge_base=$$(git merge-base origin/beta HEAD); \
    ofile=$(srcpkg)-nonfree_$(uver_nondfsg).orig.tar.gz; \
	echo "I: Exporting non-free portion of `git describe --tags $$beta_merge_base` to $$ofile"; \
	git archive --format=tar --prefix=$(srcpkg)-nonfree-$(uver_nondfsg)/ $$beta_merge_base -- \
		./Psychtoolbox/PsychBasic/*.mexa64 \
		./Psychtoolbox/PsychJava/GetCharJava.class \
		./PsychSourceGL/Cohorts/libwaffle/libwaffle*.so* \
		./Psychtoolbox/PsychBasic/Octave3LinuxFiles{,64}/{Eyelink,Datapixx}.mex \
	| gzip -9 > $$ofile; 
