#!/usr/bin/make -f
# See debhelper(7) (uncomment to enable)
# output every command that modifies files on the build system.
#export DH_VERBOSE = 1

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

NO_TESTS = bsondump mongoreplay

# Use the following vendorized deps instead of system copies
VENDORIZED_DEPS = github.com/spacemonkeygo/spacelog \
                  github.com/spacemonkeygo/openssl \
		  github.com/jessevdk/go-flags \
		  github.com/howeyc/gopass \
		  github.com/patrickmn/go-cache \
		  github.com/3rf/mongo-lint \
		  github.com/10gen/escaper \
		  github.com/10gen/llmgo \
                  gopkg.in/mgo.v2

export GOPATH = $(CURDIR)/_build
export GOBIN = $(CURDIR)/debian/bin

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

override_dh_auto_configure:
	# First create the base for all vendorized deps. This is needed to
	# avoid having dh-golang symlink a whole hierarchy (e.g. github.com)
	# under which we have vendorized deps.
	for dep in $(VENDORIZED_DEPS); do \
		mkdir -p $(CURDIR)/_build/src/$$(dirname $$dep); \
	done
	# Let dh-golang symlink all libraries from the system path
	dh_auto_configure --buildsystem=golang
	# Finally replace any symlinks to system copies with the vendorized versions
	for dep in $(VENDORIZED_DEPS); do \
		rm -f $(CURDIR)/_build/src/$$dep; \
		ln -r -s $(CURDIR)/vendor/src/$$dep $(CURDIR)/_build/src/$$dep; \
	done

override_dh_auto_build:
	for tool in $(TOOLS); do \
		go install -v -tags="ssl sasl" -ldflags -extldflags=-Wl,-z,now,-z,relro $$tool/main/$$tool.go; \
	done

override_dh_auto_test:
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	# Run only the unit tests for each tool (+ common)
	set -e; for tool in $(filter-out $(NO_TESTS),$(TOOLS)) common; do \
		cd $(CURDIR)/$$tool && go test -v -test.types=unit; \
	done
endif

override_dh_auto_install:
	# Do not install any Go source code

override_dh_auto_clean:
	rm -rf debian/bin
	rm -rf _build
	find $(CURDIR)/vendor -type f -name '*.a' -exec rm -rf {} \;
	dh_auto_clean

.PHONY: override_dh_auto_build override_dh_auto_install \
	override_dh_auto_clean override_dh_auto_test
