#!/usr/bin/make -f

srcpkg = $(shell LC_ALL=C dpkg-parsechangelog | grep '^Source:' | cut -d ' ' -f 2,2)
upstreamver = $(shell LC_ALL=C dpkg-parsechangelog | grep '^Version:' | cut -d ' ' -f 2,2 | cut -d '-' -f 1,1)
upstreamtarball = fsl-$(upstreamver)-sources.tar.gz
upstreamurl = http://fsl.fmrib.ox.ac.uk/fsldownloads/$(upstreamtarball)

# Path to the harvard-oxford-cortical-lateralized
hoxc_path = debian/fsl-harvard-oxford-atlases/usr/share/data/harvard-oxford-atlases
hoxcl_path = debian/fsl-harvard-oxford-cortical-lateralized-atlas/usr/share/data/harvard-oxford-atlases

# one ring to rule them all ...
%:
	dh $@

override_dh_auto_clean:
	rm -f data/atlases/HarvardOxford-Cortical-Lateralized.xml \
	      data/atlases/HarvardOxford/HarvardOxford-cortl*
	dh_auto_clean

override_dh_auto_build:
	: # Generating lateralized Harvard-Oxford
	debian/fsl-harvard-oxford-cortical-lateral
	dh_auto_build

# Because lateralized atlas volumes are shipped (logically) under the
# same directory (HarvardOxford/) which needs to be symlinked etc,
# -lateralized atlas depends on the stock one and we move it into
# a corresponding package later on
override_dh_install:
	dh_install
	: # Moving derived lateralized atlas into its own package
	mkdir -p $(hoxcl_path)/HarvardOxford
	mv $(hoxc_path)/HarvardOxford-Cortical-Lateralized.xml $(hoxcl_path)/
	mv $(hoxc_path)/HarvardOxford/*-cortl-* $(hoxcl_path)/HarvardOxford/

$(upstreamtarball):
	[ -f ../$@ ] || curl -o ../$@ $(upstreamurl)

maint-clean:
	rm -rf data COPYING doc

maint-update-md5sum:
	md5sum $$(find . -type f \( -path './data*' -o -name 'COPYING' -o -path './doc*' \) | sort) > debian/origdata.md5sum

maint-check-md5sum:
	# if the check fails it means upstream changed something in the
	# data -- in that case visit upstream webpage, figure out date of
	# change and use it as a new upstream version (simply update Debian
	# changelog)
	md5sum -c debian/origdata.md5sum

maint-populate-srcpkg:
	# extract the pieces we are interested in (data and license information)
	tar --wildcards --strip 1 -xvzf ../$(srcpkg)_$(upstreamver).orig.tar.gz

get-orig-source: $(upstreamtarball)
	# extract the pieces we are interested in (data and license information)
	tar --wildcards --strip 1 -xvzf ../$(upstreamtarball) fsl/data 'fsl/doc/fsl/licence.*' fsl/doc/wiki
	# convert the license into plain text file, strip parts that are irrelevant
	# the subset of stuff that we extracted
	html2text doc/fsl/licence.html | head -n73 | tail -n70 > COPYING
	rm -rf doc/fsl
	# fix permissions
	-find data -type f -name '*.nii.gz' -exec chmod -x \{\} \;
	-find data -type f -name '*.xml' -exec chmod -x \{\} \;
	# check integrity
	md5sum -c debian/origdata.md5sum
	# orig tarball
	tar --exclude='.git*' --exclude=debian \
		-cvzf ../$(srcpkg)_$(upstreamver).orig.tar.gz .
