#!/usr/bin/make -f

PERL ?= /usr/bin/perl

VER := $(shell head -1 debian/changelog | sed -e 's/^.*(//' -e 's/).*$$//')
tmp := $(CURDIR)/debian/lintian
pod2man := pod2man --center "Debian Package Checker" --release "Lintian v$(VER)"
pod2mansources := $(wildcard man/*.pod)
docsources := doc/lintian.rst README.md $(pod2mansources)
perlprovides := data/fields/perl-provides

ifneq (,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
	jobs = $(patsubst parallel=%,%,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
	PAR_ARGS=-j $(jobs)
endif

# export DH_VERBOSE=1

%:
	dh $@

override_dh_auto_build: generate-docs-stamp
# check that the static data about perl core modules is up to date
	$(PERL) -ne '/PERL_VERSION=(.+)/ and $$] > $$1 and warn q{*}x60 . qq{\n$(perlprovides) needs an update, please run\n  debian/rules refresh-perl-provides\n} . q{*}x60 . qq{\n}' $(perlprovides)


override_dh_auto_test:
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	private/runtests
endif

override_dh_clean:
	rm -rf $(CURDIR)/debian/test-out
	rm -rf doc/api.html doc/lintian.html
	rm -rf man/man1/ man/man3/ l10n/
	dh_clean

override_dh_install:
	dh_install
	echo "Setting LINTIAN_VERSION to $(VER)"
	$(PERL) -p -i -e 's/my \$$LINTIAN_VERSION;/my \$$LINTIAN_VERSION = q{$(VER)};/;' \
	    $(tmp)/usr/share/lintian/bin/*


api-doc:
	private/generate-html-docs doc/api.html

.PHONY: generate-docs
generate-docs: generate-docs-stamp

generate-docs-stamp: $(docsources)
	dh_testdir
# A UTF-8 locale seemed appropriate; manual uses &sect; character
	cd doc && LC_ALL=en_US.UTF-8 rst2html lintian.rst > lintian.html
	mkdir -p man/man1/ man/man3/
	$(pod2man) --name lintian --section=1 man/lintian.pod > man/man1/lintian.1
	set -e ; for POD in $(pod2mansources) ; do \
		BASENAME=$$(basename "$$POD" .pod) ; \
		$(pod2man) --section=1 "$$POD" > "man/man1/$$BASENAME".1 ; \
	done
	set -e ; for POD in $$(find doc/tutorial lib/Lintian lib/Test -type f '!' -path '*/Output/*' '!' -path '*/Check/*' '!' -path '*/Screen/*' ) ; do \
		BASENAME=$$(echo "$$POD" | perl -pe 's@^(doc/tutorial|lib)/@@; s@/@::@g; s/\.(pod|pm)$$//') ; \
		$(pod2man) --name="$$BASENAME" --section=3 "$$POD" > "man/man3/$$BASENAME".3 ; \
	done
	private/generate-html-docs doc/api.html > /dev/null
	touch $@

# only used manually
.PHONY: refresh-perl-provides
refresh-perl-provides:
	perl private/refresh-perl-provides > $(perlprovides)
