#!/usr/bin/make -f

include /usr/share/dpkg/pkg-info.mk
ARCHS=$(shell cd debian; ./getfromlist archlist)
LANGS=$(shell cd debian; ./getfromlist langlist)
DATE=$(shell echo $(DEB_VERSION) | cut -d '.' -f 1)
ifeq ($(DEB_DISTRIBUTION),unstable)
DEB_DISTRIBUTION=trixie
endif

ifneq (,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
DEB_PARALLEL_JOBS ?= $(patsubst parallel=%,%,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
endif

ifneq (,$(DEB_PARALLEL_JOBS))
PARALLEL=-j$(DEB_PARALLEL_JOBS)
endif

export FORCE_SOURCE_DATE=1

# Avoid “Fontconfig error: No writable cache directories” in chroots:
export HOME=$(CURDIR)/debian/fake-home

MANTMP=$(shell pwd)/debian/manual

clean:
	dh_testdir
	dh_testroot
	dh_clean build-stamp
	rm -rf $(MANTMP) $(CURDIR)/debian/fake-home
	dh_clean doc-base-stamp
	rm -rf debian/installation-guide-*.doc-base.*
	rm -rf build/build.out* build/build.tmp* build/build.po

doc-base: doc-base-stamp
doc-base-stamp:
	@echo $(ARCHS)
	rm -f $@
	rm -rf debian/installation-guide-*.doc-base.*
	set -e; cd debian && \
	    for arch in $(ARCHS); do \
		for lang in $(LANGS); do \
		    arch_full="$$(grep "^$$arch[[:space:]]" archlist | cut -f 2)"; \
		    lang_full="$$(grep "^$$lang[[:space:]]" langlist | cut -f 2)"; \
		    lang_id="$$(echo $$lang | tr A-Z a-z | sed "s/_/-/")"; \
		    sed -e "s:%ARCH%:$$arch:g" -e "s:%ARCH_FULL%:$$arch_full:g" \
			-e "s:%LANG%:$$lang:g" -e "s:%LANG_FULL%:$$lang_full:g" \
			-e "s:%LANG_ID%:$$lang_id:g" \
			TEMPLATE.doc-base >installation-guide-$$arch.doc-base.$$lang; \
		    if [ ! -e manual/$$arch/$$lang/install.$$lang.pdf ]; then \
			    sed -i "/Format: pdf/,/^$$/d" installation-guide-$$arch.doc-base.$$lang; \
		    fi; \
		done; \
	    done
	touch $@

build: build-arch build-indep

build-arch:

build-indep: build-stamp
build-stamp:
	rm -f $@
	-rm -rf $(MANTMP)
	set -e && cd build && \
		MAKEFLAGS="$(PARALLEL)" \
		official_build=1 manual_release=$(DEB_DISTRIBUTION) \
		architectures="$(ARCHS)" languages="$(LANGS)" \
		destination=$(MANTMP)/'$${arch}' noarchdir=1 \
		./build.sh
	touch $@

install: build
	dh_testdir
	dh_testroot
	dh_prep
	dh_installdirs
	
binary-arch:

binary-indep: install doc-base
	dh_testdir
	dh_testroot
	dh_installchangelogs
	for arch in $(ARCHS) ; do \
		dh_installdocs -p installation-guide-$$arch $(MANTMP)/$$arch/* ; \
	done
	dh_compress
	dh_fixperms
	dh_installdeb
	dh_gencontrol
	dh_md5sums
	dh_builddeb

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