#!/usr/bin/make -f

include /usr/share/dpkg/architecture.mk

# temporary build path (see http://golang.org/doc/code.html#GOPATH)
OUR_GOPATH := $(CURDIR)/.gopath
export GOPATH := $(OUR_GOPATH)
export GOCACHE := $(CURDIR)/.gocache

# https://blog.golang.org/go116-module-changes (TODO figure out a new solution for Go 1.17+)
export GO111MODULE := off

# riscv64 doesn't support cgo
# https://github.com/golang/go/issues/36641
ifeq (riscv64, $(DEB_BUILD_ARCH))
TAGS += no_btrfs
SKIP += github.com/containerd/containerd/snapshots/btrfs
endif

# build explicitly against Go 1.18
export PATH := /usr/lib/go-1.18/bin:$(PATH)

override_dh_gencontrol:
	# use "dh_golang" to generate "misc:Built-Using" (via "go list")
	DH_GOLANG_BUILDPKG=' \
		-tags "$(TAGS)" \
		github.com/containerd/containerd/cmd/containerd \
		github.com/containerd/containerd/cmd/containerd-shim \
		github.com/containerd/containerd/cmd/containerd-shim-runc-v1 \
		github.com/containerd/containerd/cmd/containerd-shim-runc-v2 \
		github.com/containerd/containerd/cmd/containerd-stress \
		github.com/containerd/containerd/cmd/ctr \
	' dh_golang --builddirectory='$(OUR_GOPATH:$(CURDIR)/%=%)'
	dh_gencontrol

override_dh_auto_configure:
	# copy pristine source for "/usr/share/gocode" to get into "golang-github-containerd-containerd-dev" before we muddy it with build artifacts, etc
	mkdir -p .pristine-source
	tar -c --exclude=debian --exclude=.pc --exclude=.pristine-source --exclude=vendor . | tar -xC .pristine-source
	# set up GOPATH symlink farm
	mkdir -p '$(OUR_GOPATH)/src/github.com/containerd'
	ln -sfT '$(CURDIR)' '$(OUR_GOPATH)/src/github.com/containerd/containerd'

override_dh_auto_build:
	cd '$(OUR_GOPATH)/src/github.com/containerd/containerd' \
		&& make \
			LDFLAGS='' \
			VERSION='$(shell dpkg-parsechangelog -SVersion)' \
			REVISION='' \
			BUILDTAGS='$(TAGS)' \
		&& make man

override_dh_auto_test:
ifneq (arm, $(DEB_HOST_ARCH_CPU)) # skip the tests on armhf ("--- FAIL: TestParseSelector/linux (0.00s)  platforms_test.go:292: arm support not fully implemented: not implemented")
	cd '$(OUR_GOPATH)/src/github.com/containerd/containerd' && make test SKIPTESTS='$(SKIP)'
endif

override_dh_auto_install:
	make install DESTDIR='$(CURDIR)/debian/tmp' PREFIX='/usr'
	make install-man DESTDIR='$(CURDIR)/debian/tmp' PREFIX='/usr'
	mkdir -p debian/tmp/usr/share/gocode/src/github.com/containerd \
		&& mv .pristine-source debian/tmp/usr/share/gocode/src/github.com/containerd/containerd

override_dh_installsystemd:
	dh_installsystemd
	# replace "/usr/local/bin/containerd" with "/usr/bin/containerd" in our systemd service file
	grep '/usr/local/bin/containerd' debian/*/lib/systemd/system/containerd.service \
		&& sed -i 's!/usr/local/bin/containerd!/usr/bin/containerd!g' debian/*/lib/systemd/system/containerd.service \
		&& ! grep '/usr/local/bin/containerd' debian/*/lib/systemd/system/containerd.service

%:
	dh $@
