#!/usr/bin/make -f
export DH_VERBOSE=1

include /usr/share/dpkg/pkg-info.mk
FLAKE8 := $(shell flake8 --version 2> /dev/null)

include /etc/os-release
# see https://bugs.launchpad.net/ubuntu/+source/ubuntu-advantage-tools/+bug/1840091/comments/3
ifeq (${VERSION_ID},"14.04")
APT_PKG_DEPS="apt (>= 1.0.1ubuntu2.23), apt-transport-https (>= 1.0.1ubuntu2.23), apt-utils (>= 1.0.1ubuntu2.23), libapt-inst1.5 (>= 1.0.1ubuntu2.23), libapt-pkg4.12 (>= 1.0.1ubuntu2.23) "
else ifeq (${VERSION_ID},"16.04")
APT_PKG_DEPS="apt (>= 1.2.32), apt-transport-https (>= 1.2.32), apt-utils (>= 1.2.32), libapt-inst2.0 (>= 1.2.32), libapt-pkg5.0 (>= 1.2.32)"
else ifeq (${VERSION_ID},"18.04")
APT_PKG_DEPS="apt (>= 1.6.11), apt-utils (>= 1.6.11), libapt-inst2.0 (>= 1.6.11), libapt-pkg5.0 (>= 1.6.11)"
else ifeq (${VERSION_ID},"19.04")
APT_PKG_DEPS="apt (>= 1.8.1), apt-utils (>= 1.8.1), libapt-inst2.0 (>= 1.8.1), libapt-pkg5.0 (>= 1.8.1)"
else ifeq (${VERSION_ID},"19.10")
APT_PKG_DEPS="apt (>= 1.8.1), apt-utils (>= 1.8.1), libapt-pkg5.90 (>= 1.8.1)"
endif

%:
	dh $@ --with python3,bash-completion,systemd --buildsystem=pybuild \
		--no-start

override_dh_auto_build:
	dh_auto_build
	make -C apt-hook build

override_dh_auto_test:
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	python3 -m pytest
ifdef FLAKE8
	# required for Trusty: flake8 does not install a __main__  for -m
	# invocation
	python3 $(shell which flake8) uaclient
else
	python3 -m flake8 uaclient
endif
endif

override_dh_gencontrol:
	[ -z '$(APT_PKG_DEPS)' ] || echo extra:Depends=$(APT_PKG_DEPS) >> debian/ubuntu-advantage-tools.substvars
	dh_gencontrol

override_dh_auto_install:
	dh_auto_install --destdir=debian/ubuntu-advantage-tools
	flist=$$(find $(CURDIR)/debian/ -type f -name version.py) && sed -i 's,@@PACKAGED_VERSION@@,$(DEB_VERSION),' $${flist:-did-not-find-version-py-for-replacement}
ifeq (${VERSION_ID},"14.04")
	make -C apt-hook DESTDIR=$(CURDIR)/debian/ubuntu-advantage-tools install
endif

ifeq (${VERSION_ID},"14.04")
	# Move ua-auto-attach.conf to ubuntu-advantage-pro
	mkdir -p debian/ubuntu-advantage-pro/etc/init
	mv debian/ubuntu-advantage-tools/etc/init/ua-auto-attach.conf debian/ubuntu-advantage-pro/etc/init/
	rmdir debian/ubuntu-advantage-tools/etc/init
else
	# Move ua-auto-attach.service to ubuntu-advantage-pro
	mkdir -p debian/ubuntu-advantage-pro/lib/systemd/system
	mv debian/ubuntu-advantage-tools/lib/systemd/system/ua-auto-attach.service debian/ubuntu-advantage-pro/lib/systemd/system
	cd debian/ubuntu-advantage-tools && rmdir -p lib/systemd/system
endif

override_dh_auto_clean:
	dh_auto_clean
	make clean
