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

# This Makefile has some not exactly obvious magic in it
# It is mostly based on the short dh syntax, but has some caveats:
# a) The rules file builds only the utilities located in the src/utils
#    directory. The kernel DKMS module is not built here, but on the user's
#    site. The DKMS module is packaged untouched, while the dkms.conf itself
#    is generated from the rules file, as are manual pages.
# b) The get-orig-source rebuilds the latest orig.tar.gz straight out
#    of the upstream VCS. Users of git-buildpackage can also use pristine-tar

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

MODULE_NAME := flashcache
VERSION := $(shell echo "3.1.1+git`date +%Y%m%d`")
DKMS_DIR := debian/tmp/usr/src/flashcache-$(VERSION)/
MANPAGES := $(patsubst debian/%.markdown, debian/%.8, $(wildcard debian/*.markdown))
HLP_FILES := $(patsubst %.in, %, $(wildcard debian/*.in))

# Create dynamically created files in debian/.
# This loop uses the debian/flashcache*.in input files to create
# corresponding debhelper files.
$(HLP_FILES):
	perl -pe 's{__VERSION__}{$(VERSION)}g; s{__PACKAGE__}{$(MODULE_NAME)}g;' $@.in > $@
	chmod `/usr/bin/stat -c '%a' "$@.in"` $@

$(MANPAGES):
	pandoc --standalone --to=man --output=$@ $(patsubst %.8, %.markdown, $@)

debian/flashcache-dkms.dkms:
	perl -pe 's{(PACKAGE_VERSION=).*?$$}{$${1}$(VERSION)}g; s{(MAKE=")}{$${1}COMMIT_REV=$(VERSION) }g;' src/dkms.conf > $@
	perl -pi -e 's/^(\w+)\s*=\s*([^"\n\r]+)/$$1="$$2"/g' $@

%:
	dh $@ --with dkms

override_dh_auto_clean:
	$(RM) $(MANPAGES) $(HLP_FILES) debian/flashcache-dkms.dkms
	dh_auto_clean -- -C src/utils
	dh_auto_clean -- -C man

override_dh_auto_build: $(MANPAGES) $(HLP_FILES) debian/flashcache-dkms.dkms
	dh_auto_build -- -C src/utils COMMIT_REV=$(VERSION)
	dh_auto_build -- -C man

override_dh_install:
	dh_install --fail-missing

override_dh_auto_install:
	mkdir -p $(DKMS_DIR)
	install -D -m 644  src/*.c src/*.h src/Makefile $(DKMS_DIR)
	dh_auto_install -- -C src/utils

get-orig-source:
	@set -e
	@echo "Checking out upstream package from upstream branch"
	git archive --format=tar \
		--prefix=flashcache-$(VERSION)/ upstream | \
		gzip -9 --no-name > ../flashcache_$(VERSION).orig.tar.gz

pristine-tar:
	pristine-tar commit ../flashcache_$(VERSION).orig.tar.gz upstream
