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

%:
	dh $@ --with autoreconf,python3,systemd,sphinxdoc

# use --as-needed only if supported by dh-autoreconf (to simplify backporting)
DH_AS_NEEDED=$(shell dpkg --compare-versions $$(dpkg --status dh-autoreconf | grep Version | cut -d' ' -f2) ge 6 && echo --as-needed)
override_dh_autoreconf:
	dh_autoreconf $(DH_AS_NEEDED)

ifneq (,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
PARALLEL = -j$(patsubst parallel=%,%,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
else
PARALLEL =
endif

override_dh_auto_configure:
	# Configure OVS before OVN
	test -d $(CURDIR)/ovs || mkdir ovs
	cd ovs && tar -xzf /usr/src/openvswitch/openvswitch.tar.gz --strip-components=1
	cd ovs && ./configure --enable-ssl --localstatedir=/var --sysconfdir=/etc --prefix=/usr
	# Use dh_auto_configure to build OVN
	dh_auto_configure -- \
		--prefix=/usr \
		--localstatedir=/var \
		--sysconfdir=/etc \
		--with-dbdir=/var/lib/ovn \
		--with-ovs-source=$(CURDIR)/ovs \
		--enable-ssl

# https://bugs.launchpad.net/ubuntu/+source/ovn/+bug/1956749
TEST_LIST = $(shell \
		$(CURDIR)/debian/testlist.py \
		$(CURDIR)/debian/flaky-tests.txt \
		$(CURDIR)/tests/testsuite)

override_dh_auto_test:
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	if $(MAKE) check TESTSUITEFLAGS='$(PARALLEL) $(TEST_LIST)' || \
                $(MAKE) check TESTSUITEFLAGS='--recheck'; then :; \
	else \
		cat tests/testsuite.log; \
		exit 1; \
	fi
endif # nocheck

override_dh_auto_build:
	cd ovs && $(MAKE) $(PARALLEL)
	$(MAKE) $(PARALLEL)

override_dh_auto_clean:
	dh_auto_clean
	rm -rf ovs

override_dh_installinit:
	# Package does not ship any init.d files
	dh_installinit --no-scripts

override_dh_systemd_enable:
	dh_systemd_enable -povn-central --name=ovn-northd
	dh_systemd_enable -povn-central --name=ovn-ovsdb-server-sb
	dh_systemd_enable -povn-central --name=ovn-ovsdb-server-nb
	dh_systemd_enable -povn-ic-db --name=ovn-ovsdb-server-ic-sb
	dh_systemd_enable -povn-ic-db --name=ovn-ovsdb-server-ic-nb
	dh_systemd_enable -povn-host --name=ovn-controller
	dh_systemd_enable

override_dh_systemd_start:
	dh_systemd_start --restart-after-upgrade

override_dh_python3:
	dh_python3 --shebang=/usr/bin/python3

# Helper target for creating snapshots from upstream git
DATE=$(shell date +%Y%m%d)
# Upstream branch to track
BRANCH=branch-20.03
VERSION=20.03.0

get-orig-snapshot:
	rm -Rf ovn-upstream
	git clone https://github.com/ovn-org/ovn ovn-upstream
	cd ovn-upstream && \
		git checkout $(BRANCH) && \
		export COMMIT=`git rev-parse --short HEAD` && \
		git archive --format tgz --prefix=ovn-$(VERSION)~git$(DATE).$$COMMIT/ \
			-o ../../ovn_$(VERSION)~git$(DATE).$$COMMIT.orig.tar.gz $(BRANCH)
	rm -Rf ovn-upstream
