#!/usr/bin/make -f

SOURCE := $(shell dpkg-parsechangelog | sed -ne 's,^Source: *\(.*\)$$,\1,p')
VERSION := $(shell dpkg-parsechangelog | sed -ne 's,^Version: *\(.*\)$$,\1,p')
UVERSION := $(shell echo $(VERSION) | sed -e 's/+dfsg.*//')
COMMIT := $(shell echo $(UVERSION) | sed -e 's/.*\.\([0-9abcdef]\+\)/\1/')

CFLAGS := $(shell dpkg-buildflags --get CFLAGS) \
	  $(shell dpkg-buildflags --get CPPFLAGS) -Wall -fPIC
LDFLAGS := $(shell dpkg-buildflags --get LDFLAGS)
LDLIBS := $(shell pkg-config --libs zlib liblzma) -lbz2

PYTHON2 := $(shell pyversions -r)
PYTHON3 := $(shell py3versions -r)

make_args := prefix=/usr \
	     mandir=/usr/share/man \
	     CFLAGS="$(CFLAGS)" \
	     LDFLAGS="$(LDFLAGS)" \
	     LDLIBS="$(LDLIBS)" \
	     PYTHONS="$(PYTHON2) $(PYTHON3)" \
	     zlibbundled="" \
	     zlibcppflags="" \
	     zlibldflags="$(shell pkg-config --libs zlib)"

%:
	dh $@ --with python2,python3

override_dh_auto_build:
	dh_auto_build -- all python $(make_args)

override_dh_auto_install:
	dh_auto_install -- install $(make_args)
	# Handle Python 3 extension naming - adapted from dbus-python
	# 1) Replace ".so" with EXT_SUFFIX
	# 2) Drop "module" from the filename, no longer works with python >> 3.2
	rm -f debian/tmp/usr/lib/python3/dist-packages/*.so
	set -e && for py in $(PYTHON3); do \
		so=`/usr/bin/$$py -c "import sysconfig; print(sysconfig.get_config_var('EXT_SUFFIX') or sysconfig.get_config_var('SO'))"`; \
		install $$py/_deltarpmmodule.so \
			debian/tmp/usr/lib/python3/dist-packages/_deltarpm$$so; \
	done

override_dh_auto_clean:
	mkdir -p zlib-1.2.2.f-rsyncable
	echo "clean:" > zlib-1.2.2.f-rsyncable/Makefile
	dh_auto_clean
	rm -rf python[0-9].[0-9]
	rm -rf zlib-1.2.2.f-rsyncable

override_dh_installdocs:
	dh_installdocs NEWS README

# Archive the upstream source distribution from git, removing the embedded
# copy of zlib along the way. Assumes running within a git repository that
# contains the upstream git repository. Compression is bzip2 because that's
# what official upstream tarballs are.
get-orig-source:
	case "$(UVERSION)" in \
		*+git*) git archive --format=tar --prefix=$(SOURCE)-$(UVERSION)/ $(COMMIT) | \
			bzip2 > $(SOURCE)_$(UVERSION).orig.tar.bz2 ;; \
		*) uscan --force-download --destdir . --rename --upstream-version $(UVERSION) ;; \
	esac
	cd debian \
	&& rm -rf $(SOURCE)-$(UVERSION) \
	&& bzip2 -dc ../$(SOURCE)_$(UVERSION).orig.tar.bz2 | tar xf - \
	&& rm -rf $(SOURCE)-$(UVERSION)/zlib-1.2.2.f-rsyncable \
	&& tar c --format=posix $(SOURCE)-$(UVERSION) | \
		bzip2 > ../$(SOURCE)_$(UVERSION)+dfsg.orig.tar.bz2 \
	&& rm -rf $(SOURCE)-$(UVERSION)

.PHONY: get-orig-source
