#!/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 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)


%:
	dh $@ --with python2,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)

override_dh_auto_test:
	(cd gtest && cmake . && $(MAKE) )
	(cd $(OSLOGIN_DIR)/utils && \
		$(CXX) $(CXXFLAGS) -L../../../gtest -o test_runner oslogin_utils_test.cc oslogin_utils.cc -I/usr/include/json-c $(LDFLAGS) -lcurl -ljson-c -lgtest -lpthread -lboost_regex && \
		./test_runner && \
		rm test_runner)

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

override_dh_auto_install:
	pybuild --install $(PYBUILD_OPTIONS) --dest-dir $(CURDIR)/debian/tmp
	$(MAKE) -C $(OSLOGIN_DIR) DESTDIR=$(CURDIR)/debian/tmp PAM_INSTALL_PATH=/lib/$(DEB_HOST_MULTIARCH)/security BIN_INSTALL_PATH=/usr/bin install

override_dh_installinit:
	dh_installinit --name=google-startup-scripts --onlyscripts --no-start --no-restart-on-upgrade 
	dh_installinit --name=google-shutdown-scripts --onlyscripts --no-start --no-restart-on-upgrade
	dh_installinit --name=google-shutdown-scripts-block-rsyslog --onlyscripts --no-start --no-restart-on-upgrade

override_dh_python2:
	dh_python2
	# We want to split the Python scripts out to the
	# gce-compute-image-packages package
	mkdir -p debian/gce-compute-image-packages/usr/bin/
	mv debian/python-google-compute-engine/usr/bin/* debian/gce-compute-image-packages/usr/bin/
	rmdir debian/python-google-compute-engine/usr/bin

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:
	# ForwardToConsole=yes does not seem to be a good idea, see Debian Bug #923889
	rm debian/gce-compute-image-packages/usr/lib/systemd/journald.conf.d/20-google.conf
	dh_installdeb -i

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

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

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