#!/usr/bin/make -f

package = m4
docdir = debian/tmp/usr/share/doc/$(package)

CC = gcc
CFLAGS = -g -Wall
INSTALL_PROGRAM = install

DEB_BUILD_GNU_TYPE := $(shell dpkg-architecture -qDEB_BUILD_GNU_TYPE)
DEB_HOST_GNU_TYPE := $(shell dpkg-architecture -qDEB_HOST_GNU_TYPE)

ifeq (,$(findstring noopt,$(DEB_BUILD_OPTIONS)))
  CFLAGS += -O2
endif
ifeq (,$(findstring nostrip,$(DEB_BUILD_OPTIONS)))
  INSTALL_PROGRAM += -s
endif

build:
	./configure --prefix=/usr \
		--build=$(DEB_BUILD_GNU_TYPE) --host=$(DEB_HOST_GNU_TYPE)
	$(MAKE) CC="$(CC)" CFLAGS="$(CFLAGS)"
ifeq ($(DEB_BUILD_GNU_TYPE),$(DEB_HOST_GNU_TYPE))
	$(MAKE) check
endif
	touch build

clean:
	rm -f build
	-$(MAKE) distclean
	rm -f `find . -name "*~"`
	rm -rf debian/tmp debian/files* core debian/substvars doc/$(package)

binary-indep: build
	rm -rf debian/tmp
	install -d debian/tmp/DEBIAN $(docdir)-doc debian/tmp/usr/share/doc-base
	install -m 644 debian/m4-doc debian/tmp/usr/share/doc-base
	install -m 755 debian/m4-doc.postinst debian/tmp/DEBIAN/postinst
	install -m 755 debian/m4-doc.prerm    debian/tmp/DEBIAN/prerm
	cd doc && texi2html -split_chapter $(package).texinfo
	mv doc/$(package)/*.html $(docdir)-doc
	ln -s $(package)_toc.html $(docdir)-doc/index.html
	cp -p debian/copyright $(docdir)-doc
	cp -p ChangeLog $(docdir)-doc/changelog
	cp -p debian/changelog $(docdir)-doc/changelog.Debian
	cd $(docdir)-doc && gzip -9 changelog changelog.Debian
	dpkg-gencontrol -isp -p$(package)-doc
	cd debian/tmp && \
		md5sum `find * -type f ! -regex "DEBIAN/.*"` > DEBIAN/md5sums
	chown -R root:root debian/tmp
	chmod -R go=rX debian/tmp
	dpkg --build debian/tmp ..

binary-arch: build
	rm -rf debian/tmp
	install -d debian/tmp/DEBIAN $(docdir)/examples
	cd debian/tmp && install -d usr/bin
	$(MAKE) install prefix=`pwd`/debian/tmp/usr \
		INSTALL_PROGRAM="$(INSTALL_PROGRAM)"
	cd debian && install -m 755 prerm postinst tmp/DEBIAN
	cp -p debian/changelog $(docdir)/changelog.Debian
	cp -p ChangeLog $(docdir)/changelog
	cp -p NEWS README TODO THANKS debian/copyright $(docdir)
	cp -p examples/* $(docdir)/examples
	rm -f $(docdir)/examples/Makefile*
	cd $(docdir) && gzip -9 changelog changelog.Debian
	gzip -9 debian/tmp/usr/share/info/*
	gzip -r9 debian/tmp/usr/share/man
	dpkg-shlibdeps src/$(package)
	dpkg-gencontrol -isp -p$(package)
	cd debian/tmp && \
		md5sum `find * -type f ! -regex "DEBIAN/.*"` > DEBIAN/md5sums
	chown -R root:root debian/tmp
	chmod -R go=rX debian/tmp
	dpkg --build debian/tmp ..

binary: binary-indep binary-arch

.PHONY: binary binary-arch binary-indep clean
