#!/usr/bin/make -f
# -*- makefile -*-

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

DEB_HOST_GNU_TYPE   ?= $(shell dpkg-architecture -qDEB_HOST_GNU_TYPE)
DEB_BUILD_GNU_TYPE  ?= $(shell dpkg-architecture -qDEB_BUILD_GNU_TYPE)
ifneq ($(DEB_HOST_GNU_TYPE),$(DEB_BUILD_GNU_TYPE))
	CROSS= --build $(DEB_BUILD_GNU_TYPE) --host $(DEB_HOST_GNU_TYPE)
else
	CROSS= --build $(DEB_BUILD_GNU_TYPE)
endif

ifneq (,$(findstring noopt,$(DEB_BUILD_OPTIONS)))
	CFLAGS_RELEASE = -O0 -g -DNDEBUG $(CFLAGS)
	CFLAGS_DEBUG   = -O0 -g $(CFLAGS)
else
	CFLAGS_RELEASE = -O2 -g -DNDEBUG $(CFLAGS)
	CFLAGS_DEBUG   = -O2 -g $(CFLAGS)
endif

BUILD_TYPE = Release
ifneq (,$(findstring debug,$(DEB_BUILD_OPTIONS)))
	BUILD_TYPE = Debug
endif

ifneq (,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
	NUMJOBS = $(patsubst parallel=%,%,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
	MAKEFLAGS += -j$(NUMJOBS)
endif

BUILD_FLAGS = -DCMAKE_INSTALL_PREFIX=/usr -DRESOURCEDIR=/usr/share/arpon -DCMAKE_BUILD_TYPE=$(BUILD_TYPE) \
	      -DCMAKE_C_FLAGS_RELEASE="$(CFLAGS_RELEASE)" -DCMAKE_C_FLAGS_DEBUG="$(CFLAGS_DEBUG)" 

ifneq ($(DEB_HOST_GNU_TYPE),$(DEB_BUILD_GNU_TYPE))
	BUILD_FLAGS += -DCMAKE_SYSTEM_NAME=$(shell dpkg-architecture -qDEB_BUILD_ARCH_OS) \
		       -DCMAKE_SYSTEM_PROCESSOR=$(shell dpkg-architecture -qDEB_BUILD_ARCH_CPU) \
		       -DCMAKE_C_COMPILER=$(DEB_BUILD_GNU_TYPE)-gcc
endif

CFLAGS += -Wall -Werror

debian/build/CMakeCache.txt:
	mkdir -p debian/build
	cd $(CURDIR)/debian/build && \
		cmake $(BUILD_FLAGS) ../..

debian/build: debian/build/CMakeCache.txt

build: build-stamp

build-stamp: debian/build
	dh_testdir
	$(MAKE) -C debian/build CFLAGS="$(CFLAGS)" $(MAKEFLAGS)
	touch $@

clean:
	dh_testdir
	dh_testroot
	rm -f build-stamp 
	[ ! -f Makefile ] || $(MAKE) clean
	rm -rf debian/build/
	dh_clean 

install: build
	dh_testdir
	dh_testroot
	dh_prep 
	dh_installdirs
	$(MAKE) DESTDIR=$(CURDIR)/debian/arpon install


# Build architecture-independent files here.
binary-indep: build install
# We have nothing to do by default.

# Build architecture-dependent files here.
binary-arch: build install
	dh_testdir
	dh_testroot
	dh_installchangelogs CHANGELOG
	dh_installdocs
	dh_installexamples
	dh_install
	dh_installlogrotate
	dh_installinit
	dh_installman
	dh_link
	dh_strip
	dh_compress
	dh_fixperms
	dh_makeshlibs
	dh_installdeb
	dh_shlibdeps
	dh_gencontrol
	dh_md5sums
	dh_builddeb

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