#!/usr/bin/make -f
# only the tools part of the PSMDB rules; no bazel, no C++
export DH_VERBOSE=1
export DEB_BUILD_HARDENING=1
export NJOBS=$(shell grep -c processor /proc/cpuinfo)
export TOOLSSRC=$(CURDIR)
export MONGOTOOLS=bsondump mongostat mongofiles mongoexport mongoimport mongorestore mongodump mongotop
export PATH := /usr/local/go/bin:$(PATH)

%:
	dh $@

override_dh_builddeb:
	dh_builddeb -- -Zgzip

override_dh_auto_clean:
	dh_auto_clean
	rm -fr $(TOOLSSRC)/bin
	rm -f debian/tools-build-stamp
	find $(TOOLSSRC) -name '*.pyc' -delete

# dh asks for build twice; the stamp makes the tools compile once
# (stamping is repeated in the spec and the builder, keep them in sync)
compile-mongo-tools: debian/tools-build-stamp
	@:

debian/tools-build-stamp:
	mkdir -p $(TOOLSSRC)/bin $(TOOLSSRC)/../src/github.com/mongodb
	rm -rf $(TOOLSSRC)/../src/github.com/mongodb/mongo-tools
	cp -r $(TOOLSSRC) $(TOOLSSRC)/../src/github.com/mongodb/mongo-tools
	export GOROOT="/usr/local/go/"; \
        export GOPATH=$(TOOLSSRC)/../; \
        export PATH="/usr/local/go/bin:$(PATH):$(GOPATH)"; \
        export GOBINPATH="/usr/local/go/bin"
	cd $(TOOLSSRC)/../src/github.com/mongodb/mongo-tools; \
        sed -i '/^\t"github.com\/craiggwilson\/goke\/pkg\/git"$$/d' buildscript/build.go; \
        sed -i '/^\tversionStr, err := runCmd(ctx, "go", "run", "release\/release.go", "get-version")$$/,/failed to get git commit hash/{/failed to get git commit hash/{N;d};d}' buildscript/build.go; \
        sed -i "s:versionStr,:\"$(PSMDB_TOOLS_REVISION)\",:" buildscript/build.go; \
        sed -i "s:gitCommit):\"$(PSMDB_TOOLS_COMMIT_HASH)\"):" buildscript/build.go; \
        ./make build;
	cp -av $(TOOLSSRC)/../src/github.com/mongodb/mongo-tools/bin/* $(TOOLSSRC)/bin
	touch $@

# upstream only logs stamping/tag failures, so check the binaries
verify-mongo-tools:
	./bin/mongodump --version | grep -q "^mongodump version: $(PSMDB_TOOLS_REVISION)$$" \
	    || { echo "ERROR: version stamping failed"; ./bin/mongodump --version; exit 1; }
	ldd bin/mongodump | grep -q libgssapi_krb5 \
	    || { echo "ERROR: built without the gssapi build tag"; ldd bin/mongodump; exit 1; }

build: compile-mongo-tools verify-mongo-tools
	@:

override_dh_auto_install:
	dh_auto_install
	cp -av $(TOOLSSRC)/bin/* debian/percona-server-mongodb-tools/usr/bin

# plain -dbg package, named like percona-server-mongodb-dbg, not a .ddeb
override_dh_strip:
	dh_strip -a --dbg-package=percona-server-mongodb-tools-dbg
