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

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) | cut -d '-' -f 1,1 )

modulesfile = debian/ants.environment-modules

export  http_proxy=http://127.0.0.1:9/
export  https_proxy=http://127.0.0.1:9/

export DEB_LDFLAGS_MAINT_APPEND = -Wl,--as-needed

ifneq (,$(findstring noopt,$(DEB_BUILD_OPTIONS)))
    export CFLAGS += -O0
else
    export CFLAGS += -O2
endif

# Uncomment this to turn on verbose mode.
export DH_VERBOSE=1

# Exclude all heavy tests while building on slowish build
# bots/platforms
BOGOMIPS = $(shell awk '/^bogomips/{print $$3;}' /proc/cpuinfo | sed -ne '1s,\..*,,gp' )
CTEST_EXCLUDE = $(shell [ "$(BOGOMIPS)" -gt 2000 ] || echo "-E '^ANTS(_|PSE)'")

# Default mega-rule
%:
	dh $@ --parallel


override_dh_auto_configure:
	dh_auto_configure -- \
		-DANTS_SUPERBUILD:BOOL=OFF \
		-DANTS_USE_GIT_PROTOC:BOOL=OFF \
		-DCOPY_SCRIPT_FILES_TO_BIN_DIR:BOOL=OFF \
		-DCMAKE_SKIP_RPATH:BOOL=OFF \
		-DUSE_SYSTEM_ITK:BOOL=ON \
		-DUSE_VTK:BOOL=OFF \
		-DBUILD_SHARED_LIBS:BOOL=ON \
		-DRUN_SHORT_TESTS:BOOL=ON \
		-DRUN_LONG_TESTS:BOOL=OFF \
		-DEXECUTABLE_OUTPUT_PATH:PATH=$(DESTBINDIR) \
		--debug-output

%modules: %modules.in
	sed -e 's,$$UVERSION,$(uver),g' $< >| $@

override_dh_auto_build: $(modulesfile)
	dh_auto_build
	: Build manpages
	cd `/bin/ls -d obj-*/bin` && mkdir -p ../man && \
    for f in *; do \
	 help2man --name="part of ANTS registration suite" --version-string $(uver) \
	          --no-info --no-discard-stderr ./$$f >| ../man/$$f.1; \
     done


override_dh_auto_test:
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	cd obj-*; \
	 ln -s ../debian/testdata ExternalData || : ; \
	 ctest --force-new-ctest-process $(CTEST_EXCLUDE)
else
	: # Skip unittests due to nocheck
endif

override_dh_auto_install:
	dh_auto_install
	: remove .so files 
	rm debian/ants/usr/lib/*.so
	: Move binaries under usr/lib/ants
	mv debian/ants/usr/bin/* debian/ants/usr/lib/ants
	: Symlink binaries of primary importance into /usr/bin
	for f in ANTS WarpImageMultiTransform; do \
		dh_link usr/lib/ants/$$f usr/bin/$$f; \
	done
	: Install shell scripts
	install -t debian/ants/usr/lib/ants Scripts/*
	: Install modules file
	install -m 664 $(modulesfile) debian/ants/usr/share/modules/modulefiles/ants/$(uver)
	: Adjust ANTSPATH
	cd debian/ants/usr/lib/ants && sed -ie 's,\([^"=]*\(/bin/ants\|ANTS/release/bin\)\),/usr/lib/ants,g' *.sh *.pl && rm *.she *.ple
	: Install manpages
	dh_installman obj-*/man/*

override_dh_auto_clean:
	dh_auto_clean
	rm -rf $(BUILDDIR) debian/ants.environment-modules

# upstream tests use some tiny dataset for tests, which
# they deposited online instead of keeping under the GIT
# Since the data size is small, we just package it along,
# but that would require first building ANTs
get_upstream_external_data:
	mkdir -p .ExternalData/MD5
	# TODO
