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

FSLMAJORVERSION = 4.1

# enable exented globbing in the shell to be able to use more
# sophisticated stuff in dh_install files
SHELL := /bin/bash -O extglob

# get octave paths (have to build-depend on octave-headers)
include /usr/share/octave/debian/defs.make

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

# specify all FSL projects that shall be built
PROJECTS = \
  utils fslio miscmaths newimage libhfunc libvis first_lib meshclass fslvtkio \
  misc_tcl basisfield warpfns bint shapeModel MVdisc libmeshutils \
  avwutils bet2 cluster fast4 feat5 film filmbabe flirt fabber fslpres fslvbm \
  mcflirt melodic misc_c miscvis mm randomise siena slicetimer susan tbss \
  fnirt fugue misc_scripts fdt first possum sgeutils flameo

# specify FSL extras to be built
EXTRAS = libprob libcprob cprob

# set essential config vars for FSL build process
FSLDIR=$(CURDIR)
FSLCONFDIR=$(FSLDIR)/config

ifneq (,$(findstring noopt,$(DEB_BUILD_OPTIONS)))
	OPTFLAGS = -O0
else
	# -O3 seems to kill GCC for some pieces on some architectures, sometimes
	# (miscmaths, avwutils)
	OPTFLAGS = -O2
endif

# default compiler flags
# apply to FSL as 'ANSI_FLAGS'
CFLAGS = -Wall -g -DHAVE_LIBFREETYPE -fPIC \
         -I/usr/include/nifti \
         -I/usr/include/newmat \
         -I$(FSLDIR)/extras/src/libprob -I$(FSLDIR)/extras/src/libcprob \
         -I$(FSLDIR)/src

# default linker flags
# apply to FSL as 'ARCHLDFLAGS'
LDFLAGS = -Wl,--no-undefined -L/usr/lib/fsl/lib
# 'as-needed' kills everything -- symbols of C libs get confused
# and results change -- remember cprob:gamma()
#LDFLAGS = -Wl,--no-undefined -Wl,--as-needed -L/usr/lib/fsl/lib

# where are the internal libs
FSL_LIBRARY_PATH=$(CURDIR)/lib

# install into this directory
DEB_DESTDIR=$(CURDIR)/debian/tmp

# define common environment setup for all make calls
# complicated LD_LIBRARY expression ensures that no
# trailing colon ends up in LD_LIBRARY_PATH
DEB_BUILD_ENV=LD_LIBRARY_PATH=$(FSL_LIBRARY_PATH)$${LD_LIBRARY_PATH:+:$${LD_LIBRARY_PATH}} \
		FSLDIR="$(FSLDIR)" \
		FSLCONFDIR="$(FSLCONFDIR)" \
		DEB_DESTDIR="$(DEB_DESTDIR)" \
		OPTFLAGS="$(OPTFLAGS)" \
		ANSI_FLAGS="$(CFLAGS)" \
		DEPENDFLAGS="$(CFLAGS)" \
		ARCHLDFLAGS="$(LDFLAGS)"

controlfiles:
	# inject current FSL major version into all templates
	for f in debian/templates/*; do \
		sed -e "s/#FSLMVERSION#/$(FSLMAJORVERSION)/g" $$f \
			> debian/$$(basename $$f) ; \
	done
	# renamed files that need to have a version-specific name
	for suffix in 1 desktop dirs install links lintian-overrides manpages menu postinst docs; do \
		for prefix in fsl fsl-doc nudge; do \
		[ -f debian/$$prefix.$$suffix ] &&  \
			mv debian/$$prefix.$$suffix debian/$$prefix-$(FSLMAJORVERSION).$$suffix || true ; \
		done ; \
	done
	# and rename the meta-package files
	for f in debian/meta.*; do \
		target=$$(basename $$f); suffix=$${target#*.} ; \
		mv $$f debian/fsl.$$suffix; \
	done

cleancontrolfiles:
	# clean sed'ed files and intermediate rubbish
	for f in debian/templates/*; do\
		rm -f debian/$$(basename $$f) ; \
	done
	rm -f debian/fsl.preinst
	# versioned files
	rm -f debian/{fsl,fsl-doc,nudge}-$(FSLMAJORVERSION).{1,desktop,dirs,install,links,lintian-overrides,manpages,menu,postinst,preinst,docs}

# build and install extra
biextra-%:
	$(DEB_BUILD_ENV) $(MAKE) -C extras/src/$*
	$(DEB_BUILD_ENV) $(MAKE) -C extras/src/$* install

# cleanup extra
cextra-%:
	$(DEB_BUILD_ENV) $(MAKE) -C extras/src/$* distclean

# build and install sub-project
biproj-%:
	$(DEB_BUILD_ENV) $(MAKE) -C src/$*
	$(DEB_BUILD_ENV) $(MAKE) -C src/$* install

# cleanup sub-project
cproj-%:
	$(DEB_BUILD_ENV) $(MAKE) -C src/$* distclean

# build and install all extras
biextras: $(EXTRAS:%=biextra-%)

# clean all extras
cextras: $(EXTRAS:%=cextra-%)
	find extras/src -name '*.o' -delete


instdir:
# FSL does not separate build and install properly
# create temporary install dir now
	if [ ! -d $(DEB_DESTDIR) ]; then mkdir -p $(DEB_DESTDIR); fi
	dh_installdirs

# build and install all sub-projects
biprojs: $(PROJECTS:%=biproj-%)

# cleanup all sub-projects
cprojs: $(PROJECTS:%=cproj-%)


#Architecture
build: build-arch build-indep
build-arch: build-stamp
build-indep: build-stamp
build-stamp: instdir biextras biprojs
	dh_testdir

	# fix permissions
	find debian/tmp/tcl/BWidget -type f -exec chmod -x {} \;
	chmod 644 debian/tmp/tcl/*.{tcl,xbm,ppm,ico}
	chmod -x debian/tmp/etc/{flirtsch,fslpres}/*

	# cleanup TCL stuff
	rm -r debian/tmp/tcl/BWidget/BWMan/
	find debian/tmp/tcl/BWidget/ -name '*.txt' -delete

	# remove FSL internal binary and scripts
	rm debian/tmp/bin/{fslpres,eqn2gif,makehtmeqns}

	# silence lintian warning about a script which is actually documentation
	let "RES = $$(wc -l < src/possum/doc/readme) -1" \
		&& tail -n$${RES} src/possum/doc/readme > debian/tmp/doc/possum/readme

	# generate debhelper file to create /usr/bin symlinks and manpage links
	# for all relevant binaries installed by the versioned FSL package
	for f in $$(find debian/tmp/bin \! -type d \! -name Runtcl); do \
		bname=$$(basename $$f); \
		echo "/usr/lib/fsl/$(FSLMAJORVERSION)/fsl_app_wrapper /usr/bin/fsl$(FSLMAJORVERSION)-$$bname" >> debian/fsl-$(FSLMAJORVERSION).links ; \
		echo "/usr/share/man/man1/fsl-$(FSLMAJORVERSION).1.gz /usr/share/man/man1/fsl$(FSLMAJORVERSION)-$${bname}.1.gz" >> debian/fsl-$(FSLMAJORVERSION).links ; \
	done
	touch $@


clean: cleancontrolfiles controlfiles cextras cprojs
	dh_testdir
	dh_testroot

	# remove leftovers
	find $(CURDIR) -name '*.so' -delete
	-rm src/fdt/{xfibres,fdt_matrix_ops,indexer,replacevols,probtrackx,reord_OM,sausages,probtrack_old}
	-rm src/feat5/doc/{top.html,feat.tcl}
	-rm -r etc/standard lib

	# clean the remaining temp dir
	rm -rf include

	# finally clean package
	dh_clean

	# fix permissions in the source
	find src/ -name '*.fig' -or -name '*.gif' -exec chmod -x {} \;

	-rm build-stamp


# checks that the included desktop files are ok
validate-desktop-files:
	for f in $(CURDIR)/debian/desktop/*.desktop; do \
		desktop-file-validate $${f} ; \
	done


install: build
	# make FSL logo for menu entries
	convert debian/tmp/tcl/fsl-logo-tiny.ppm \
		-resize x32 -crop 32x32+6+0 debian/tmp/fsl-$(FSLMAJORVERSION).xpm

	# install fsl config
	cp -r -t debian/tmp etc
	# clean useless pieces
	rm debian/tmp/etc/fslconf/fslmachtype.sh


# Must not depend on anything. This is to be called by
# binary-arch/binary-indep
# in another 'make' thread.
binary-common:
	dh_testdir
	dh_testroot
	dh_install
	dh_installchangelogs
	dh_installman
	dh_installdocs
	dh_installmenu
	dh_lintian
	dh_link
	dh_strip
	dh_compress
	dh_fixperms
	dh_installdeb
	# dh_shlibdeps needs access to the private libs
	dh_shlibdeps -l $(FSL_LIBRARY_PATH)
	# get the correct dependency for octave
	octave-depends
	dh_gencontrol
	dh_md5sums
	dh_builddeb


# Build architecture independent packages using the common target.
binary-indep: install
	dh_installdirs -i

	# install docs (except images which are in fsl package)
	cp -r doc/!(images) debian/fsl-doc-$(FSLMAJORVERSION)/usr/share/fsl/$(FSLMAJORVERSION)/doc
	# wipe installer script - useless on Debian
	rm debian/fsl-doc-$(FSLMAJORVERSION)/usr/share/fsl/$(FSLMAJORVERSION)/doc/fsl/fsl_installer.sh

	# cleanup doc path
	rm debian/tmp/doc/feat5/DO
	-rm debian/tmp/doc/fsl/fsl_installer.sh

	# clean empty dirs from doc package
	find debian/fsl-doc-$(FSLMAJORVERSION)/usr/share/fsl/$(FSLMAJORVERSION)/doc -depth -type d -empty -exec rmdir {} \;
	find debian/tmp/doc -depth -type d -empty -exec rmdir {} \;

	$(MAKE) -f debian/rules DH_OPTIONS=-i binary-common


# Build architecture dependant packages using the common target.
binary-arch: install
	dh_installdirs -a

	# remove previous link to make repeated builds work
	-rm debian/fsl-$(FSLMAJORVERSION)/usr/share/fsl/$(FSLMAJORVERSION)/etc/fslconf/{feat.tcl,fsl.sh}

	# set execute permission for GUI application wrapper
	chmod +x debian/fsl_app_wrapper

	# install a symlink to the main data. directory -- later on we might want to
	# have more fine-grained linking and abandon the global link
	ln -sf ../data debian/fsl-$(FSLMAJORVERSION)/usr/share/fsl/$(FSLMAJORVERSION)/data

	$(MAKE) -f debian/rules DH_OPTIONS=-a binary-common


binary: binary-arch binary-indep
.PHONY: build clean binary-indep binary-arch binary
