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

# This has to be exported to make some magic below work.
export DH_OPTIONS

arch=$(shell dpkg --print-architecture )
ifeq ($(arch), amd64)
 # directory suffix for octave
 arch64=64
 # matlab extensions
 mexext=a64
else
 arch64=
 mexext=glx
endif

%:
	dh $@

# 		echo "D: for $$fname mfile is $$mfile";
override_dh_install:
	dh_install
	dh_install -poctave-psychtoolbox-3-nonfree \
		Psychtoolbox/PsychBasic/Octave3LinuxFiles$(arch64)/*.mex \
		usr/lib/psychtoolbox-3/PsychtoolboxAddons/
	dh_install -pmatlab-psychtoolbox-3-nonfree \
		Psychtoolbox/PsychBasic/*.mex$(mexext) \
		usr/lib/matlab/site/psychtoolbox-3/
	: # fix permissions
	find debian/*psychtoolbox* -name *.mex* | xargs chmod a-x
	find debian/*psychtoolbox* -name *.mex* -ls

# we need to add links as well into corresponding subdirectories under
# /usr/share/psychtoolbox-3 -- locate by the location of .m file and symlink nearby
# That is why build-depends on octave-psychtoolbox-3
override_dh_link:
	: # Octave pieces
	link_exts() { \
	  pkg=$$1; ext=$$2; \
	  rm -f debian/$$pkg.links; \
	  set -e; /usr/bin/find debian/$$pkd -name *.$$ext | \
	  while read f; do \
		fname=$$(basename $$f); fdir=$$(dirname $$f); \
		mfile=$$(/usr/bin/find /usr/share/psychtoolbox-3 -name $${fname%.$$ext}.m); \
		[ ! -z "$$mfile" ] || mfile=$$(/usr/bin/find /usr/share/psychtoolbox-3 -name $${fname%.$$ext}.mex); \
		[ ! -z "$$mfile" ] && mdir=$$(dirname $$mfile) || { echo "no $$mfile for ext $$ext fname $$f. skipping";  continue; }; \
		echo "/usr/lib$${f#*usr/lib}	$$mdir/$$fname" >> debian/$$pkg.links; \
	  done; };  \
	link_exts octave-psychtoolbox-3-nonfree mex; \
	link_exts matlab-psychtoolbox-3-nonfree mex$(mexext)
	: # Manually adding few links where there is no .m
	echo "/usr/lib/matlab/site/psychtoolbox-3/PsychOpenHMDVRCore.mexa64    /usr/share/psychtoolbox-3/PsychBasic/PsychOpenHMDVRCore.mexa64" >> debian/matlab-psychtoolbox-3-nonfree.links
	dh_link

# failed to figure out how to please dh_shlibdeps
disable_override_dh_shlibdeps:
	dh_shlibdeps
	for p in matlab-psychtoolbox-3-nonfree octave-psychtoolbox-3-nonfree; do \
		echo "D: harvesting shlibs for $$p"; \
		find debian/$$p -type f -name \*.mex\* \
		| grep -v 'Eyelink\.mex' \
		| xargs dpkg-shlibdeps --ignore-missing-info -Tdebian/$$p.substvars debian/$$p; done

# For portability to older systems which do not support default (since
# buster) .xz for components of the .deb
override_dh_builddeb:
	dh_builddeb -- -Zgzip

override_dh_clean:
	dh_clean
	: # Prune some Debian generated files
	-rm debian/*-nonfree.links

