#!/usr/bin/make -f

export DH_VERBOSE=1

DEB_HOST_ARCH ?= $(shell dpkg-architecture -qDEB_HOST_ARCH)

DEB_VERSION := $(shell dpkg-parsechangelog -SVersion | sed 's/-[^-]*$$//')
UPSTREAM_VERSION := $(DEB_VERSION)
SOFTWARE_NAME := actionlint

# The toolchain Build-Depends pins golang-<x.y>-go (rendered from the tag's
# toolchain.json): its compiler lives in /usr/lib/go-<x.y>/bin, while
# /usr/bin/go comes from the golang-go meta — which is not installed when
# the versioned BD alternative satisfies the build. Put the highest
# installed toolchain bin dir first on PATH; no-op when the meta's own
# compiler is installed (that is the same directory).
GO_TOOLCHAIN_BIN := $(shell ls -d /usr/lib/go-*/bin 2>/dev/null | sort -V | tail -n 1)
ifneq (,$(GO_TOOLCHAIN_BIN))
export PATH := $(GO_TOOLCHAIN_BIN):$(PATH)
endif

export GOTOOLCHAIN=local
export GOPROXY=off
export GOSUMDB=off
export GOMODCACHE=$(CURDIR)/.gomodcache
# Launchpad sbuild sets HOME to unwritable /sbuild-nonexistent; keep the
# build cache inside the build tree.
export GOCACHE=$(CURDIR)/.gocache
export CGO_ENABLED=0

%:
	dh $@

override_dh_auto_build:
	# vendor/ is unpacked by dpkg-source from the orig-vendor component.
	@test -d vendor -a -f vendor/modules.txt || { \
		echo "ERROR: vendor/ missing; orig-vendor component did not unpack" >&2; \
		exit 1; \
	}

	go build \
		-v -trimpath -mod=vendor -modcacherw -buildvcs=false \
		-ldflags "-s -w -buildid=" \
		-o $(SOFTWARE_NAME) ./cmd/$(SOFTWARE_NAME)

	@test -f $(SOFTWARE_NAME) || (echo "ERROR: binary not built" && exit 1)
	@echo "==> Binary built successfully: $(SOFTWARE_NAME)"

override_dh_auto_install:
	install -Dm755 $(SOFTWARE_NAME) $(CURDIR)/debian/$(SOFTWARE_NAME)/usr/bin/$(SOFTWARE_NAME)
	install -Dm644 LICENSE.txt $(CURDIR)/debian/$(SOFTWARE_NAME)/usr/share/doc/$(SOFTWARE_NAME)/copyright

override_dh_auto_test:

override_dh_strip:
