#!/usr/bin/make -f

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

PKD   = $(abspath $(dir $(MAKEFILE_LIST)))
PKG   = $(word 2,$(shell dpkg-parsechangelog -l$(PKD)/changelog | grep ^Source))
PKV  ?= $(shell dpkg-parsechangelog -l$(PKD)/changelog -SVersion)

export DH_GOPKG := github.com/coreos/rkt
export DH_GOLANG_BUILDPKG := $(DH_GOPKG)/api/v1alpha $(DH_GOPKG)/rkt
export DH_GOLANG_INSTALL_ALL := 1

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

override_dh_clean:
	dh_clean
	## 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/_workspace/src -mindepth 1 -type d -empty -delete -printf 'removed %p\n'

override_dh_auto_configure:
## Prefer bundled libraries, if any:
	mkdir -p _build
	cp -r Godeps/_workspace/src _build/
####
	dh_auto_configure
	$(RM) -rvf _build/src/src/$(DH_GOPKG)
	mkdir -p   _build/src/src/$(DH_GOPKG)
	cp -r rkt _build/src/src/$(DH_GOPKG)/
## appc-cni needs special handling:
	mkdir -p _build/src/$(DH_GOPKG)/Godeps/_workspace/src/github.com/containernetworking
	cp -r _build/src/github.com/containernetworking/cni _build/src/$(DH_GOPKG)/Godeps/_workspace/src/github.com/containernetworking/
## appc-spec needs special handling:
	mkdir -p _build/src/$(DH_GOPKG)/Godeps/_workspace/src/github.com/appc
	cp -r _build/src/github.com/appc/spec _build/src/$(DH_GOPKG)/Godeps/_workspace/src/github.com/appc/
####
	perl -0nE 'say $$1 if m{^Files\-Excluded\:\s*(.*?)(?:\n\n|Files:|Comment:)}sm;' debian/copyright \
        | while read D; do D="$${D##Godeps/_workspace/src/}" ; printf "Patching 3rd party includes: $$D\n" ;\
            perl -pi -E "s{$(DH_GOPKG)/Godeps/_workspace/src/$$D}{$$D}msg;" `find _build/src -type f -name "*"` ;\
        done

override_dh_auto_build:
	## Build Stage1 .aci image, see "Documentation/hacking.md":
	mkdir _build/src2 \
        && cp -r _build/src _build/src2
	cd _build/src/$(DH_GOPKG) \
        && sh ./autogen.sh \
        && ./configure \
            --enable-tpm=no \
            --with-stage1-flavors=host \
            --with-stage1-default-name=host \
            --with-stage1-default-version=$(PKV) \
            --with-stage1-default-location=/usr/lib/rkt/stage1-host.aci
	$(MAKE) -C _build/src/$(DH_GOPKG) manpages GOPATH="$(CURDIR)"/_build/src2
	$(MAKE) -C _build/src/$(DH_GOPKG) bash-completion GOPATH="$(CURDIR)"/_build/src2
	$(MAKE) -C _build/src/$(DH_GOPKG) BUILDDIR="$(CURDIR)"/_build GOPATH="$(CURDIR)"/_build/src2

override_dh_auto_test:
	-dh_auto_test

override_dh_install:
	dh_install -XLICENSE.MIT
