#!/usr/bin/make -f

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

include /usr/share/dpkg/pkg-info.mk

export DH_GOPKG := github.com/rkt/rkt
export DH_GOLANG_BUILDPKG := $(DH_GOPKG)/api/v1alpha $(DH_GOPKG)/rkt
#export DH_GOLANG_EXCLUDES := $(DH_GOPKG)/pkg/tpm
export DH_GOLANG_INSTALL_ALL := 1

export HOME := $(CURDIR)/debian/tmp

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

PB_GO_FILES = $(patsubst %.proto, %.pb.go, $(wildcard */*/*.proto))
$(PB_GO_FILES):
	protoc -I "$(dir $@)" --go_out=plugins=grpc:$(dir $@) $(@:.pb.go=.proto)

override_dh_clean:
	dh_clean $(PB_GO_FILES)
	## 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 vendor -mindepth 1 -type d -empty -delete -printf 'removed %p\n'

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

override_dh_auto_build:
	## Build Stage1 .aci image, see "Documentation/hacking.md":
	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=$(DEB_VERSION) \
            --with-stage1-default-location=/usr/lib/rkt/stage1-host.aci
	$(MAKE) -C _build/src/$(DH_GOPKG) BUILDDIR="$(CURDIR)"/_build GOPATH="$(CURDIR)"/_build
	$(MAKE) -C _build/src/$(DH_GOPKG) bash-completion GOPATH="$(CURDIR)"/_build
	$(RM) -rvf _build/src/github.com/rkt/rkt/vendor
	$(MAKE) -C _build/src/$(DH_GOPKG) manpages GOPATH="$(CURDIR)"/_build

override_dh_auto_test:
	-dh_auto_test

override_dh_install:
	dh_install -XLICENSE.MIT -Xpkg/tpm

override_dh_installsystemd:
	dh_installsystemd
#	dh_installsystemd --name=rkt-api --no-enable --no-start
#	dh_installsystemd --name=rkt-api-tcp --no-enable --no-start
#	dh_installsystemd --name=rkt-metadata --no-enable --no-start
	dh_installsystemd --name=cni-dhcp --no-enable --no-start
	dh_installsystemd --name=rkt-gc
