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

export DH_VERBOSE=1

srcpkg = $(shell LC_ALL=C dpkg-parsechangelog | awk '/^Source:/{print $$2;}')
uversion = $(shell LC_ALL=C dpkg-parsechangelog | awk '/^Version:/{print $$2;}' | sed -e 's,-[^-]*$$,,g')

MANDIR=$(CURDIR)/debian/manpages

CFLAGS = -Wall -g

ifneq (,$(findstring noopt,$(DEB_BUILD_OPTIONS)))
  CFLAGS += -O0
else
  CFLAGS += -O2
endif

# Following logic was borrowed from strace Debian package
# Copyright 1996-2011 strace Debian maintainers, License: BSD-3

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

DEB_BUILD_GNU_TYPE := $(shell dpkg-architecture -qDEB_BUILD_GNU_TYPE)
DEB_HOST_GNU_TYPE := $(shell dpkg-architecture -qDEB_HOST_GNU_TYPE)
DEB_HOST_ARCH := $(shell dpkg-architecture -qDEB_HOST_ARCH)

ifeq ($(DEB_HOST_GNU_TYPE),$(DEB_BUILD_GNU_TYPE))
  CONFIG_OPTS = --build=$(DEB_BUILD_GNU_TYPE)
else
  CONFIG_OPTS = --build=$(DEB_BUILD_GNU_TYPE) --host=$(DEB_HOST_GNU_TYPE)
endif

%:
	dh $@

override_dh_auto_configure:
	dh_auto_configure $@
	: # Need to generate strace-4.6/Makefile with proper architecture specs
	: # otherwise build would fail on 32/64 kernel with 32bit userland
	cd strace-4.6; \
		sh ./configure --prefix=/usr $(CONFIG_OPTS)

override_dh_auto_install:
	make install DESTDIR=debian/cde PREFIX=/usr

override_dh_auto_clean:
	-dh_auto_clean $@
	@echo "I: distcleaning in strace-4.6"
	-cd strace-4.6 && make distclean

# make orig tarball from repository corresponding to $srcpkg (should
# contain treeish) but excluding some content
get-orig-source:
	git archive --worktree-attributes --format=tar \
		--prefix=$(srcpkg)-$(uversion)/ v$(uversion) \
        | gzip -9 >| ../tarballs/$(srcpkg)_$(uversion).orig.tar.gz

manpages: build
	@echo "I: Pre-generating manpages"
	mkdir -p $(MANDIR)
	for b in cde cde-exec; do \
		help2man --no-info --no-discard-stderr --help-option=-h \
			--opt-include=$(MANDIR)/$$b.inc \
			--version-string=$(uversion) ./$$b \
			>| $(MANDIR)/$$b.1; \
	done