#!/usr/bin/make -f

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

# Exit immediately if any untested command fails
SHELL := sh -e

# Path of 'debian' directory
DEB_DIR := $(abspath $(dir $(MAKEFILE_LIST)))

# Use Makefile snippets provided by dpkg-dev (>= 1.16)
DPKG_EXPORT_BUILDFLAGS = 1
include /usr/share/dpkg/default.mk

# Temporary directory
TMPDIR := $(DEB_DIR)/tmp-dir

# The upstream Makefiles are written in a way that suppresses the recipe
# echoing. This means that tools like 'blhc' cannot inspect the build logs.
# Instead of maintaining a patch that will remove the preceding '@' symbol
# from all recipes, we pass the '--trace' flag to make, which prints the
# entire recipe to be executed, even for recipes that are normally silent
MAKEFLAGS += --trace

D := $(DEB_DIR)/suckless-tools
TOOLS := $(filter-out debian, $(wildcard *))


%:
	dh $@

.PHONY: override_dh_auto_clean
override_dh_auto_clean:
	for TOOL in $(TOOLS); do \
		dh_auto_clean --sourcedirectory=$${TOOL}; \
	done

.PHONY: override_dh_auto_build
override_dh_auto_build:
	for TOOL in $(TOOLS); do \
		dh_auto_build --sourcedirectory=$${TOOL}; \
	done

.PHONY: override_dh_auto_install
override_dh_auto_install:
	for TOOL in $(TOOLS); do \
		dh_auto_install --sourcedirectory=$${TOOL} -- PREFIX=/usr; \
	done

.PHONY: override_dh_installdocs
override_dh_installdocs:
	dh_installdocs
	for TOOL in $(TOOLS); do \
		cp $${TOOL}/README $(D)/usr/share/doc/suckless-tools/README.$${TOOL}; \
	done


# --------------------------------------------------------------------
# http://wiki.debian.org/onlyjob/get-orig-source
#
# As per policy §4.9, this target may be invoked in any directory, but
# '/usr/share/dpkg/pkg-info.mk' will not work unless we are at package's
# top level directory (i.e. dpkg-parsechangelog finds the changelog file at
# 'debian/changelog').
# So we invoke '_get-orig-source' from package's top level directory.
.PHONY: get-orig-source _get-orig-source
get-orig-source:
	$(MAKE) -C $(DEB_DIR)/.. -f debian/rules _get-orig-source SAVEDIR=$(CURDIR)

_get-orig-source:
	@echo "# Create temporary directory '$(TMPDIR)'"
	$(RM) -r $(TMPDIR)
	mkdir -p $(TMPDIR)
	@echo "# Download upstream tarballs"
	uscan --noconf --no-symlink --destdir=$(TMPDIR) --check-dirname-level=0 \
		--force-download --download-current-version $(DEB_DIR)
	# Move packages to current working directory, as required by policy,
	# and create the appropriate symlinks using mk-origtargz.
	cd $(SAVEDIR) && \
	for pkg in $$(ls $(TMPDIR)); do \
		pkgname=$$(echo $${pkg} | sed -r 's/([^-]+)-[0-9].*/\1/'); \
		cp $(TMPDIR)/$${pkg} .; \
		mk-origtargz --package $(DEB_SOURCE) --symlink \
			--version $(DEB_VERSION_UPSTREAM) $${pkg}; \
		rename "s/\.orig\./.orig-$${pkgname}./" \
			$(DEB_SOURCE)_$(DEB_VERSION_UPSTREAM).orig.*; \
	done
	@echo "# Clean up temporary directory"
	$(RM) -r $(TMPDIR)
