#!/usr/bin/make -f

export PYBUILD_NAME=google-compute-engine
export PYBUILD_TEST_PYTEST=1
export PYBUILD_DIR=packages/python-google-compute-engine
export PYBUILD_TEST_ARGS={dir}/packages/google_compute_engine/

OSLOGIN_DIR=packages/google-compute-engine-oslogin

DEB_HOST_MULTIARCH ?= $(shell dpkg-architecture -qDEB_HOST_MULTIARCH)

# this breaks with more than one requested versions for Python 2 or Python3 but they are not likely to appear in Xenial or Trusty
PYBUILD_OPTIONS = -i python{version} -p $(shell pyversions -vr 2>/dev/null) -d $(PYBUILD_DIR)
PYBUILD3_OPTIONS = -i python{version} -p $(shell py3versions -vr 2>/dev/null) -d $(PYBUILD_DIR)


%:
	dh $@ --with python2,python3,systemd --buildsystem=pybuild

override_dh_auto_configure:
	cp -r /usr/src/gtest/ ./
	# dh-pyhon before 2.20160609 passes --dir . to pybuild without option to override, thus call pybuild directly
	pybuild --configure $(PYBUILD_OPTIONS)
	pybuild --configure $(PYBUILD3_OPTIONS)

override_dh_auto_test:
	(cd gtest && cmake . && $(MAKE) )
	make -C $(OSLOGIN_DIR)/test CXXFLAGS="$(CXXFLAGS) -I$(CURDIR)/gtest" LDLIBS="-lpthread -lcurl -ljson-c -lboost_regex" GTEST_DIR=$(CURDIR)/gtest

override_dh_auto_build:
	pybuild --build $(PYBUILD_OPTIONS)
	pybuild --build $(PYBUILD3_OPTIONS)
	$(MAKE) -C $(OSLOGIN_DIR) all

override_dh_auto_install:
	pybuild --install $(PYBUILD_OPTIONS) --dest-dir $(CURDIR)/debian/tmp
	pybuild --install $(PYBUILD3_OPTIONS) --dest-dir $(CURDIR)/debian/tmp
	$(MAKE) -C $(OSLOGIN_DIR) DESTDIR=$(CURDIR)/debian/tmp LIBDIR=/lib PAMDIR=/lib/$(DEB_HOST_MULTIARCH)/security install

override_dh_link-indep:
	rm -f debian/gce-compute-image-packages/etc/dhcp/dhclient-exit-hooks \
		debian/gce-compute-image-packages/etc/dhcp/dhclient-exit-hooks.d/google_set_hostname
	dh_link -i

override_dh_installdeb-indep:
	rm -rf debian/gce-compute-image-packages/etc/init
	dh_installdeb -i

override_dh_systemd_start:
	# Configured in gce-compute-image-packages.postinst instead.

override_dh_python3:
	dh_python3
	# We want to split the Python 3 scripts out to the
	# gce-compute-image-packages package
	mkdir -p debian/gce-compute-image-packages/usr/bin/
	mv debian/python3-google-compute-engine/usr/bin/* debian/gce-compute-image-packages/usr/bin/
	rmdir debian/python3-google-compute-engine/usr/bin

override_dh_python2:
	dh_python2
	# We don't want the Python 2 scripts at all
	rm -rf debian/python-google-compute-engine/usr/bin

override_dh_clean:
	dh_clean packages/google_compute_engine.egg-info/ gtest/ .pybuild/

override_dh_auto_clean:
	$(MAKE) -C $(OSLOGIN_DIR) clean
	$(MAKE) -C $(OSLOGIN_DIR)/test clean
	pybuild --clean $(PYBUILD_OPTIONS)
	pybuild --clean $(PYBUILD3_OPTIONS)
