#!/usr/bin/make -f
include /usr/share/dpkg/pkg-info.mk

# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1

# Acceptance tests need to be run separately.
export DH_GOPKG := github.com/prometheus/alertmanager
export DH_GOLANG_EXCLUDES := test/.*/acceptance examples asset
export DH_GOLANG_EXCLUDES_ALL := 0
export DH_GOLANG_INSTALL_EXTRA := template/default.tmpl ui/app

BUILDDIR := $(CURDIR)/build
METAPKG := github.com/prometheus/common

BRANCH     := debian/sid
USER       := team+pkg-go@tracker.debian.org
BUILD_DATE  = $(shell date --utc --date='@$(SOURCE_DATE_EPOCH)' \
    +%Y%m%d-%H:%M:%S)
GO_VERSION  = $(shell go version | sed 's/go version \(\S*\).*/\1/')
GCCGO       = $(strip $(shell go version | grep gccgo))
VERSION     = $(shell echo '$(DEB_VERSION_UPSTREAM)' | tr '~' '-')
BUILDFLAGS  = -ldflags \
  " -X $(METAPKG)/version.Version=$(VERSION)\
    -X $(METAPKG)/version.Revision=$(DEB_VERSION)\
    -X $(METAPKG)/version.Branch=$(BRANCH)\
    -X $(METAPKG)/version.BuildUser=$(USER)\
    -X $(METAPKG)/version.BuildDate=$(BUILD_DATE)\
    -X $(METAPKG)/version.GoVersion=$(GO_VERSION)"

%:
	dh $@ --buildsystem=golang --builddirectory=$(BUILDDIR)

WHATIS1 := "prometheus-alertmanager \\- The Prometheus alert manager"
WHATIS2 := "promtool \\- Tooling for the Prometheus alert manager"

override_dh_auto_build:
	dh_auto_build -- $(BUILDFLAGS)
	mv -v $(BUILDDIR)/bin/alertmanager $(BUILDDIR)/bin/prometheus-alertmanager
	# Build bash completion scripts.
	mkdir -vp $(BUILDDIR)/bash_completion.d
	$(BUILDDIR)/bin/amtool --completion-script-bash > \
	    $(BUILDDIR)/bash_completion.d/amtool
	# Build man pages.
	mkdir -vp $(BUILDDIR)/man
	$(BUILDDIR)/bin/prometheus-alertmanager --help-man > \
	    $(BUILDDIR)/man/prometheus-alertmanager.1
	$(BUILDDIR)/bin/amtool --help-man > \
	    $(BUILDDIR)/man/amtool.1
	# Remove build information headers, and fix whatis entry.
	sed -i '/^  /d; /^.SH "NAME"/,+1c.SH "NAME"\n'$(WHATIS1) \
	    $(BUILDDIR)/man/prometheus-alertmanager.1
	sed -i '/^  /d; /^.SH "NAME"/,+1c.SH "NAME"\n'$(WHATIS2) \
	    $(BUILDDIR)/man/amtool.1
	# Fix executable path in amtool examples
	sed -i 's/\.\/amtool/amtool/' $(BUILDDIR)/man/amtool.1

execute_after_dh_auto_test:
	# Don't abort if acceptance tests fail, as they are too sensitive to
	# timing issues.
	( for pkg in cli/acceptance with_api_v1/acceptance \
	    with_api_v2/acceptance; do \
	    DH_GOLANG_EXCLUDES= DH_GOPKG=$(DH_GOPKG)/test/$$pkg \
	    dh_auto_test || { \
		echo "*** Acceptance tests failed ***"; \
		exit 1; \
		}; \
	  done; ) || true

override_dh_auto_install-indep:
	dh_auto_install -- --no-binaries
	dh_install usr/share/gocode

override_dh_auto_install-arch:
	dh_auto_install -- --no-source
