#!/usr/bin/make -f

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

TIMESTAMP := $(shell date -d @$(SOURCE_DATE_EPOCH) -u +%Y-%m-%dT%H:%M:%SZ)

export DH_GOPKG := github.com/arduino/arduino-cli
LDFLAGS := -X $(DH_GOPKG)/internal/version.versionString=$(DEB_VERSION_UPSTREAM)
LDFLAGS += -X $(DH_GOPKG)/internal/version.commit=$(DEB_VERSION)
LDFLAGS += -X $(DH_GOPKG)/internal/version.date=$(TIMESTAMP)

export DH_GOLANG_INSTALL_EXTRA := \
	internal/arduino/security/keys \
	internal/cli/configuration/configuration.schema.json \
	$(wildcard internal/locales/data/*.po)

# Exclude some packages from tests and -dev package
# - integrationtest: tests fail with the message: "Error searching for repository root path"
export DH_GOLANG_EXCLUDES := internal/integrationtest

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

execute_before_dh_auto_build:
	# Copy pb library to its forked path to apply two patches from arduino-cli authors, see https://github.com/cmaglie/pb
	mkdir debian/build/src/github.com/cmaglie
	cp -r debian/build/src/gopkg.in/cheggaaa/pb.v1 debian/build/src/github.com/cmaglie/pb
	patch -p1 -d debian/build/src/github.com/cmaglie/pb < debian/missing-sources/cmaglie-pb-added-finishprintover-function.patch
	patch -p1 -d debian/build/src/github.com/cmaglie/pb < debian/missing-sources/cmaglie-pb-protected-access-to-setunits-and-setmaxwidth.patch

# Only build the main and docsgen binaries. The other binaries are not meant
# to be included in the arduino-cli package.
override_dh_auto_build:
	DH_GOLANG_BUILDPKG="$(DH_GOPKG) $(DH_GOPKG)/internal/docsgen" dh_auto_build -- -ldflags '$(LDFLAGS)'

# Do not install binaries automatically. Install them manually instead to
# prevent including docsgen in arduino-cli package.
override_dh_auto_install:
	dh_auto_install -- --no-binaries

execute_before_dh_install:
	debian/build/bin/docsgen docs/commands

execute_before_dh_installman:
	TMP=$$(mktemp -d); \
	HOME=$$TMP debian/build/bin/arduino-cli generate-docs manpage -o debian/tmp; \
	rm -rf $$TMP
