#!/usr/bin/make -f

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

# dh-go builds the main module from a local go.work, so the toolchain embeds
# its version as "(devel)" and "desync version" would not report the release.
# Inject it at link time the same way upstream's goreleaser config does. The
# variable is main.version in the installed binary, but in the test binary the
# command package is linked under its import path, so set both (-X ignores
# symbols that don't exist).
GO_LDFLAGS := '-ldflags=-X=main.version=$(DEB_VERSION_UPSTREAM) \
	-X=github.com/folbricht/desync/cmd/desync.version=$(DEB_VERSION_UPSTREAM)'

# Upstream imports github.com/go-ini/ini, whose Debian package is a symlink
# to gopkg.in/ini.v1 (its go.mod declares "module gopkg.in/ini.v1"). Map it
# explicitly so the generated go.work does not point both module paths at the
# same directory, which Go rejects.
export DH_GOLANG_MODULE_MAPPINGS := github.com/go-ini/ini:gopkg.in/ini.v1

%:
	dh $@ --builddirectory=debian/_build --buildsystem=golang --with=golang

override_dh_auto_build:
	dh_auto_build -- $(GO_LDFLAGS)

override_dh_auto_test:
	# Skip TestMountIndex - requires a working FUSE mount via fusermount
	# which is not available in Debian build chroots.
	#
	# Skip TestDocumentationLinks - it checks the upstream Markdown docs,
	# which dh-golang does not copy into the build directory.
	dh_auto_test -- $(GO_LDFLAGS) \
		-test.skip="^(TestMountIndex|TestDocumentationLinks)$$"

# Trim the CLI sources and the test fixtures from the source shipped in the
# -dev package. Nothing imports github.com/folbricht/desync/cmd/..., and
# testdata/ is ~11MB of binary blobs plus a throwaway TLS CA which are of no
# use to library consumers.
#
# The excludes are scoped to dh_auto_install rather than exported globally:
# DH_GOLANG_EXCLUDES also filters the targets handed to "go install" and
# "go test", so exporting it would stop the desync binary being built and the
# upstream test suite being run.
override_dh_auto_install:
	DH_GOLANG_EXCLUDES='^cmd/ (^|/)testdata/' dh_auto_install

# Generate man page from the --help/--version output with help2man.
ifeq (,$(findstring nodoc, $(DEB_BUILD_OPTIONS)))
execute_after_dh_auto_build:
	help2man -N \
		-n "desync" \
		--version-string='$(DEB_VERSION_UPSTREAM)' \
		-o debian/desync.1 \
		debian/_build/bin/desync
endif
