#!/usr/bin/make -f

# DH_VERBOSE := 1

DEBPKGNAME     := $(shell dpkg-parsechangelog | awk '/^Source:/ {print $$2}')
DEBVERS        := $(shell dpkg-parsechangelog | awk '/^Version:/ {print $$2}')
VERSION        := $(shell echo '$(DEBVERS)' | sed -e 's/^[0-9]*://' -e 's/-.*//')
MANDIR=$(CURDIR)/debian/$(DEBPKGNAME)/usr/share/man/man1/
HELP2MAN = help2man --no-info --version-string="$(VERSION)" --no-discard-stderr --help-option=" "
# --help-option=" -h" # does not work in all cases

%:
	dh $@

override_dh_install:
	dh_install
	debian/install.pl -prefix debian/$(DEBPKGNAME)/usr -taxonomy /var/lib/$(DEBPKGNAME)/taxonomy -scriptpath "../share/perl5/KronaTools/scripts"

override_dh_installman_does_not_work__giving_up:
	dh_installman
	mkdir -p $(MANDIR)
	set -x ; \
	for script in debian/$(DEBPKGNAME)/usr/bin/* ; do \
	    name=`basename $${script}` ; \
	    pscript=`echo $${name} | sed 's:^kt\(.*\):\1.pl:'` ; \
	    pl="KronaTools/scripts/$${pscript}" ; \
	    title=`$${pl} | grep -A 2 '^Description:' | tail -n 1` ; \
	    if [ "$${title}" = "" ] ; then \
	        title=`$${pl} | grep -A2 -- \" - $${pscript} \" | tail -n1` ; \
	    fi ; \
	    if [ "$${title}" = "" ] ; then \
	        title="$${name} from KronaTools package" ; \
	    fi ; \
	    NAME=`echo $${name} | tr 'a-z' 'A-Z'` ; \
	    PSCRIPT=`echo $${pscript} | tr 'a-z' 'A-Z'` ; \
	    $(HELP2MAN) --name="$${title}" $${pl} | \
	        sed -e '/^.[IP]P/{;N;s/^.[IP]P\n____.*//;}' \
	            -e '/^.[IP]P/{;N;s/^.[IP]P\n____.*//;}' \
	            -e "s/$${pscript}/$${name}/g" \
	            -e "s/$${PSCRIPT}/$${NAME}/g" \
	        > $(MANDIR)/$${name}.1 ; \
	done
