#!/usr/bin/make -f
# -*- makefile -*-

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

export DH_GOLANG_INSTALL_ALL := 1

# Some tests fail, see upstream report https://github.com/mongodb/mongo-tools/issues/67
export DH_GOLANG_EXCLUDES := github.com/mongodb/mongo-tools/bsondump \
                             github.com/mongodb/mongo-tools/common/archive \
                             github.com/mongodb/mongo-tools/common/intents \
                             github.com/mongodb/mongo-tools/common/log

export GOPATH := $(CURDIR)/obj-$(DEB_BUILD_GNU_TYPE)
export GOBIN := $(GOPATH)/bin

USE_EMBEDDED := $(shell . /etc/lsb-release; [ $$DISTRIB_RELEASE \< 16.04 ] && echo true || echo false)

COMMON_FLAGS:= -x -v -tags ssl

TOOLS := bsondump mongostat mongofiles mongoexport mongoimport \
         mongorestore mongodump mongotop mongooplog

%:
	dh $@ --with=golang --buildsystem=golang

override_dh_auto_configure:
	dh_auto_configure
	# dh-golang's configure has copied the source tree into GOPATH. But
	# because mongo-tools gets some dependencies from the archive and some
	# from the copies bundled in dist, we have to unpick a bunch of what it
	# has done and set it up again.

	# Remove the extra copy of vendor dh-golang has copied onto GOPATH.
	rm -Rf ${GOPATH}/src/github.com/mongodb/mongo-tools/vendor

	# Move the mongo-tools source aside while we do this.
	mv ${GOPATH}/src/github.com/mongodb/mongo-tools ${GOPATH}/mongo-tools.tmp

	# Clean GOPATH.
	rm -Rf ${GOPATH}/src

ifeq ($(USE_EMBEDDED), true)
	# If we get all dependencies from vendor, just copy it onto GOPATH.
	cp -R vendor/src ${GOPATH}
else
	# If not, link depedencies from vendor or from where the distro package
	# has installed it, as appropriate.

	# Packaged dependencies
	debian/helpers/link-from-installed github.com/jacobsa/oglematchers
	debian/helpers/link-from-installed github.com/jessevdk/go-flags
	debian/helpers/link-from-installed golang.org/x/crypto
	debian/helpers/link-from-installed gopkg.in/mgo.v2
	debian/helpers/link-from-installed gopkg.in/tomb.v2

	# Packages that aren't in the archive (or aren't at the right versions
	# in the archive)
	debian/helpers/link-from-bundled github.com/3rf/mongo-lint
	debian/helpers/link-from-bundled github.com/howeyc/gopass
	debian/helpers/link-from-bundled github.com/smartystreets/goconvey
	debian/helpers/link-from-bundled github.com/spacemonkeygo/openssl
	debian/helpers/link-from-bundled github.com/spacemonkeygo/spacelog
endif

	# And put the mongo-tools source back again.
	mkdir -p ${GOPATH}/src/github.com/mongodb/
	mv ${GOPATH}/mongo-tools.tmp ${GOPATH}/src/github.com/mongodb/mongo-tools

override_dh_auto_build:
	for tool in $(TOOLS); do \
		go install $(COMMON_FLAGS) $$tool/main/$$tool.go; \
	done

override_dh_auto_test:
	dh_auto_test -- -tags ssl

override_dh_auto_install:
	mkdir -p debian/juju-mongo-tools3.2/usr/lib/juju/mongo3.2/bin
	install $(GOBIN)/* debian/juju-mongo-tools3.2/usr/lib/juju/mongo3.2/bin

