#!/usr/bin/make -f

PKD  = $(abspath $(dir $(MAKEFILE_LIST)))
PKG  = $(word 2,$(shell dpkg-parsechangelog -l$(PKD)/changelog | grep ^Source))
VER ?= $(shell dpkg-parsechangelog -l$(PKD)/changelog | perl -ne 'print $$1 if m{^Version:\s*([\d\.]+)}')

export DH_GOPKG = gitlab.com/gitlab-org/gitlab-ci-multi-runner
export DH_GOPKG_common = $(DH_GOPKG)/common
#export DH_GOLANG_INSTALL_EXTRA := vendor
#export DH_GOLANG_INSTALL_ALL := 1
#export DH_GOLANG_EXCLUDES = apps/gitlab-runner-helper

## Set some build variables as per Makefile:
GO_LDFLAGS ?= \
    -X $(DH_GOPKG_common).NAME=$(PKG) \
    -X $(DH_GOPKG_common).REVISION=$(VER)
#    -X $(DH_GOPKG_common).VERSION=$(VERSION)
#    -X $(DH_GOPKG_common).BUILT=$(BUILT)
#    -X $(DH_GOPKG_common).BRANCH=$(BRANCH)

MKPI=debian/mk-prebuilt-images.sh

%:
	dh $@ --buildsystem=golang --with=golang,systemd --builddirectory=_build --paralel

override_dh_clean:
	dh_clean $(MKPI)
	## Remove Files-Excluded (when built from checkout or non-DFSG tarball):
	$(RM) -rv `perl -0nE 'say $$1 if m{^Files\-Excluded\:\s*(.*?)(?:\n\n|Files:|Comment:)}sm;' debian/copyright`
	-find Godeps -type d -empty -delete -print

$(MKPI):
	sed -e 's/__VERSION__/$(VER)/g' $@.in > $@
	chmod --reference=$@.in $@

override_dh_auto_configure: $(MKPI)
	dh_auto_configure
	cp -v --no-dereference vendor _build/src/gitlab.com/gitlab-org/gitlab-ci-multi-runner/

override_dh_auto_build:
	dh_auto_build --parallel -- \
            -ldflags "$(GO_LDFLAGS)"

override_dh_auto_install:
	dh_auto_install --destdir=debian/tmp

override_dh_auto_test:
	mkdir -v -p $(CURDIR)/debian/tmp
	HOME=$(CURDIR)/debian/tmp \
        dh_auto_test -- \
            -ldflags "$(GO_LDFLAGS)"
