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

version = 0.8
date = 20240305

destdir=debian/tmp
mandir=/usr/share/man
docdir=/usr/share/doc/tklib
exampledir=$(docdir)/examples

%:
	dh $@

override_dh_auto_build:
	dh_auto_build
	$(MAKE) doc

override_dh_auto_install:
	dh_auto_install --destdir=$(destdir)
	#
	find $(destdir)/usr/lib -name repair.tcl -delete
	#
	# Now set the permissions properly, since the Makefile doesn't bother
	find $(destdir)/usr/lib -type f -print | xargs chmod 644
	#
	# Fix application manpages
	cd $(destdir)$(mandir)/mann && \
	  for f in diagram-viewer.n bitmap-editor.n shtmlview.n ; do \
	    sed -e'/\.so man.macros/ d' \
	    	-e's/^\.TH \([^ ]\+\) n/.TH \1 1/' \
		-e's/clock(n)/clock(3tcl)/g' \
		-e's/(n)/(3tk)/g' \
		-e's/(3)/(3tk)/g' \
		-e's/spIf/sp 1\nIf/' \
		-e's/\.sp Fu/\.sp 1\nFu/' \
		$$f > `basename $$f .n`.1; \
	    rm $$f; \
	  done
	#
	# Several manpages has incorrect filenames (in lowercase), so take them
	# from the headers
	# Also, replace section n by 3tk
	cd $(destdir)$(mandir)/mann && \
	  for f in *.n ; do \
	    name=`grep '^\.TH' <$$f | sed 's/^\.TH "\([^ ]\+\)".*/\1/'`; \
	    sed -e'/\.so man.macros/ d' \
	    	-e's/^\.TH \([^ ]\+\) n/.TH \1 3tk/' \
		-e's/clock(n)/clock(3tcl)/g' \
		-e's/(n)/(3tk)/g' \
		-e's/(3)/(3tk)/g' \
		-e's/spIf/sp 1\nIf/' \
		-e's/\.sp Fu/\.sp 1\nFu/' \
		-e's/"A dialog which allows a user to m/"M/' \
		$$f > $$name.3tk; \
	    rm $$f; \
	  done
	#
	# cleanup docs
	cd doc/html && \
	  for f in *.html ; do \
	    sed -i -e's/clock(n)/clock(3tcl)/g' \
	    	-e's/(n)/(3tk)/g' \
	    	-e's/(3)/(3tk)/g' $$f; \
	  done
	#
	# generate documentation index
	tclsh debian/genindex.tcl doc/html >doc/html/index.html

override_dh_installexamples:
	dh_installexamples
	#
	# Fix incorrect permissions
	find debian/tklib$(exampledir) -type f -print | xargs chmod 644
	#
	# Fix canvas example
	convert -geometry 400x300 debian/tklib$(exampledir)/canvas/morgens.jpg \
				  debian/tklib$(exampledir)/canvas/morgens1.jpg
	mv -f debian/tklib$(exampledir)/canvas/morgens1.jpg \
	      debian/tklib$(exampledir)/canvas/morgens.jpg
	sed -i -e 's/^source/#source/' \
	       -e 's/256/100/' debian/tklib$(exampledir)/canvas/puzzle.tcl

override_dh_compress:
	dh_compress -Xusr/share/doc/tklib/examples/ \
		    -Xusr/share/doc/tklib/html

override_dh_gencontrol:
	tcltk-depends
	dh_gencontrol

override_dh_auto_test:
	# Tests require X, so disable them

get-orig-source:
	wget -O tklib_$(version)~$(date).orig.tar.gz \
		https://core.tcl.tk/tklib/tarball/Tk+Library+Source+Code.tar.gz?r=trunk:$(date)

.PHONY: override_dh_auto_install override_dh_installexamples override_dh_gencontrol \
	override_dh_auto_test get-orig-source
