#!/usr/bin/make -f

export DH_GOPKG := github.com/danos/xpath-plugins

GOBUILDDIR := _build
GO_PATH := $(CURDIR)/$(GOBUILDDIR)

# From version 1.38 onwards, dh-golang inserts the all/trimpath flags into
# any build that is not manually overridden.  We therefore need to match this
# for the plugins to load - if we don't, they will fail to load due to a
# package mismatch error (which in reality means the path to the common yang
# repo is different prior to the GOPATH root directory).
#
# Prior to version 1.38, dh-golang does not use these flags, so we don't
# either.  This requires that we use GOBUILDDIR in both plugin and plugin-
# using code so the paths match, which is fragile, but proven to work.
#
DH_GOLANG_VER := $(shell dpkg-query -W -f='$${Version}' dh-golang)
BUILD_ARGS_GO := $(if $(shell dpkg --compare-versions $(DH_GOLANG_VER) ge 1.38 && echo true),-gcflags=all=-trimpath="$(GO_PATH)/src" -asmflags=all=-trimpath="$(GO_PATH)/src",)

# If the cover tool is present, use it in tests
GOCOVER=$(if $(shell go doc cmd/cover >/dev/null 2>&1 && echo true),-cover,)

%:
	dh $@ --with systemd,golang --buildsystem=golang --builddirectory=$(GOBUILDDIR)

# AFAICT, each separate plugin needs a 'GOPATH ... go build ...' entry here.
override_dh_auto_build: vet
	cd $(GOBUILDDIR)/src; \
	GOPATH=$(GO_PATH) \
	go build $(BUILD_ARGS_GO) -buildmode=plugin \
		-o intf_leafref_plugin.so \
		github.com/danos/xpath-plugins/interface-leafref-plugin/;
	cd $(GOBUILDDIR)/src; \
	GOPATH=$(GO_PATH) \
	go build $(BUILD_ARGS_GO) -buildmode=plugin \
		-o qos_profile_validation_plugin.so \
		github.com/danos/xpath-plugins/qos-profile-validation-plugin/;
	cd $(GOBUILDDIR)/src; \
	GOPATH=$(GO_PATH) \
	go build $(BUILD_ARGS_GO) -buildmode=plugin \
		-o siad_link_speed_plugin.so \
		github.com/danos/xpath-plugins/siad-link-speed-plugin/;
	cd $(GOBUILDDIR)/src; \
	GOPATH=$(GO_PATH) \
	go build $(BUILD_ARGS_GO) -buildmode=plugin \
		-o vif_interface_plugin.so \
		github.com/danos/xpath-plugins/vif-interface-plugin/;

override_dh_strip:
	dh_strip -X/opt/vyatta/lib/interface-leafref-plugin/intf_leafref_plugin.so; \
	dh_strip -X/opt/vyatta/lib/qos-profile-validation-plugin/qos_profile_validation_plugin.so
	dh_strip -X/opt/vyatta/lib/siad-link-speed-plugin/siad_link_speed_plugin.so
	dh_strip -X/opt/vyatta/lib/vif-interface-plugin/vif_interface_plugin.so

override_dh_auto_test:
	dh_auto_test -- $(GOCOVER)

# We do not vet vendor code
vet:
	if go doc cmd/vet >/dev/null 2>&1; then \
		GOPATH=$(CURDIR)/$(GOBUILDDIR) go vet $$(find . -type f -name \*.go | \
	    xargs dirname | sort -u | grep -v "/vendor/"); \
	fi
