#!/usr/bin/make -f

include /usr/share/dpkg/pkg-info.mk

export DH_VERBOSE = 1
export LC_ALL = C.UTF-8
export BUILDBOT_VERSION = $(DEB_VERSION_UPSTREAM)
export PYTHONDONTWRITEBYTECODE = 1

ifneq (,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
NUMJOBS = $(patsubst parallel=%,%,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
MAKEFLAGS += -j$(NUMJOBS)
else
NUMJOBS = 1
endif

override_dh_auto_clean \
override_dh_auto_configure \
override_dh_auto_build:
	$(@:override_%=%) --buildsystem=pybuild --sourcedirectory=master \
		--package=buildbot
	$(@:override_%=%) --buildsystem=pybuild --sourcedirectory=worker \
		--package=buildbot-worker
	@case $@ in \
	override_dh_auto_clean) \
		echo "$(MAKE) -C master/docs clean && $(RM) _trial_temp/"; \
		$(MAKE) -C master/docs clean && rm -rf _trial_temp/; \
		;; \
	override_dh_auto_build) \
		echo "$(MAKE) -C master/docs html JOBS=$(NUMJOBS)"; \
		$(MAKE) -C master/docs html JOBS=$(NUMJOBS); \
		;; \
	esac

test_env = \
	SQLALCHEMY_SILENCE_UBER_WARNING=1 \
	PYTHONPATH=pkg:{destdir}/{install_dir} \
	PATH=$$PATH:{destdir}/usr/bin
test_command = trial3 --reporter=text buildbot.test buildbot_worker.test

debian/tmp/manpages/%: debian/manpages/%.scdoc
	mkdir -p $(@D)
	scdoc < $< > $@

manpages_src = $(wildcard debian/manpages/*.scdoc)
manpages = $(addprefix debian/tmp/manpages/,$(notdir $(manpages_src:.scdoc=)))

override_dh_auto_install: $(manpages)
	dh_auto_install --buildsystem=pybuild --sourcedirectory=master \
		--package=buildbot
	dh_auto_install --buildsystem=pybuild --sourcedirectory=worker \
		--package=buildbot-worker
	dh_auto_install --sourcedirectory=master/docs \
		--package=buildbot-doc --destdir=debian/buildbot-doc
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	dh_auto_test --buildsystem=pybuild -- --system=custom \
		--test-args='$(test_env) $(test_command)'
endif

override_dh_auto_test:
	:

override_dh_installinit:
	dh_installinit --no-scripts

override_dh_installsystemd:
	dh_installsystemd --no-enable --no-start -r --no-restart-after-upgrade
	set -e; if test -d debian/buildbot/lib/systemd/system; then \
		ln -s /dev/null debian/buildbot/lib/systemd/system/buildbot.service; \
		ln -s /dev/null debian/buildbot-worker/lib/systemd/system/buildbot-worker.service; \
	else \
		ln -s /dev/null debian/buildbot/usr/lib/systemd/system/buildbot.service; \
		ln -s /dev/null debian/buildbot-worker/usr/lib/systemd/system/buildbot-worker.service; \
	fi

%:
	dh $@ --with python3,bash-completion,sphinxdoc
