#!/usr/bin/make -f

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

include /usr/share/dpkg/default.mk

SHELL    := sh -e
SOURCE := $(shell dpkg-parsechangelog -SSource)
VERSION := $(shell dpkg-parsechangelog -SVersion)
VERSION_UPSTREAM := $(shell echo "$(VERSION)" | sed -e 's,-[^-]*$$,,')
VERSION_BINNMU := $(shell echo "$(VERSION)" | sed -rne 's,.*\+b([0-9]+)$$,\1,p')

include debian/rules.defs

setup: debian/control
	dh_testdir
	$(MAKE) -f debian/rules.gen setup_$(DEB_HOST_ARCH)

build: build-arch build-indep

build-arch: setup
	dh_testdir
	$(MAKE) -f debian/rules.gen build-arch_$(DEB_HOST_ARCH)

build-indep: setup
	dh_testdir
	$(MAKE) -f debian/rules.gen build-indep

maintainerclean:
	rm -f debian/control* debian/rules.gen debian/xen-hypervisor-* debian/xen-utils-[0-9]*

clean: debian/control
	dh_testdir
	rm -rf $(BUILD_DIR) $(STAMPS_DIR) debian/lib/python/debian_xen/__pycache__
	dh_clean

binary-indep:
	dh_testdir
	$(MAKE) -f debian/rules.gen binary-indep

binary-arch:
	dh_testdir
	$(MAKE) -f debian/rules.gen binary-arch_$(DEB_HOST_ARCH)

binary:	build-arch binary-indep binary-arch

DIR_ORIG = ../orig/$(SOURCE)-$(VERSION_UPSTREAM)
TAR_ORIG_NAME = $(SOURCE)_$(VERSION_UPSTREAM).orig.tar.xz
TAR_ORIG = $(firstword $(wildcard ../$(TAR_ORIG_NAME)) $(wildcard ../orig/$(TAR_ORIG_NAME)))

orig: $(DIR_ORIG)
	rsync --delete --exclude /debian --exclude .git -a $(DIR_ORIG)/ .
	QUILT_PATCHES='$(CURDIR)/debian/patches' QUILT_PC=.pc quilt push --quiltrc - -a -q --fuzz=0

$(DIR_ORIG):
ifeq ($(TAR_ORIG),)
	$(error Cannot find orig tarball $(TAR_ORIG_NAME))
else
	mkdir -p ../orig
	tar -C ../orig -xaf $(TAR_ORIG)
endif

CONTROL_FILES += debian/changelog debian/bin/gencontrol.py $(wildcard debian/templates/*.in) 
CONTROL_FILES += $(wildcard debian/arch/defines) $(wildcard debian/arch/*/defines)
GENCONTROL = $(__MODULES_DIR)gencontrol.py
debian/control debian/rules.gen: $(CONTROL_FILES)
ifeq ($(wildcard debian/control.md5sum),)
	$(MAKE) -f debian/rules debian/control-real
else ifeq ($(VERSION_BINNMU),)
	md5sum --check debian/control.md5sum --status || \
		$(MAKE) -f debian/rules debian/control-real
else
	grep -v debian/changelog debian/control.md5sum | md5sum --check - --status || \
		$(MAKE) -f debian/rules debian/control-real
endif

debian/control-real: $(CONTROL_FILES)
	debian/bin/gencontrol.py
	md5sum $^ > debian/control.md5sum
	@echo
	@echo This target is made to fail intentionally, to make sure
	@echo that it is NEVER run during the automated build. Please
	@echo ignore the following error, the debian/control file has
	@echo been generated SUCCESSFULLY.
	@echo
	exit 1

.PHONY: clean build binary-indep binary-arch binary
