#!/usr/bin/make -f

INSTALL = install
INSTALL_FILE    = $(INSTALL) -p    -o root -g root  -m  644
INSTALL_PROGRAM = $(INSTALL) -p    -o root -g root  -m  755
INSTALL_SCRIPT  = $(INSTALL) -p    -o root -g root  -m  755
INSTALL_DIR     = $(INSTALL) -p -d -o root -g root  -m  755

package=deets
CFLAGS = -Wall -g

CONFIGFLAGS = --prefix=/usr --mandir=/usr/share/man LDFLAGS="-Wl,--as-needed -g"

ifneq (,$(findstring noopt,$(DEB_BUILD_OPTIONS)))
CFLAGS += -O0
else
CFLAGS += -O2
endif

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


obj:
	mkdir $@

configure: stamp-configure
stamp-configure: obj
	$(checkdir)
	cd obj && ../configure CFLAGS="$(CFLAGS)" $(CONFIGFLAGS)
	touch $@


build: stamp-build
stamp-build: stamp-configure
	$(checkdir)
	cd obj && $(MAKE)
	touch $@

install: build
	cd obj && $(MAKE) install DESTDIR=$(CURDIR)/debian/deets

binary: binary-arch
binary-arch: stamp-build install checkroot
	$(INSTALL_DIR) debian/deets/usr/share/doc/deets/examples
	$(INSTALL_FILE) debian/copyright debian/deets/usr/share/doc/deets
	$(INSTALL_FILE) debian/changelog debian/deets/usr/share/doc/deets/changelog.Debian
	$(INSTALL_FILE) README debian/deets/usr/share/doc/deets/README
	$(INSTALL_FILE) example.lua debian/deets/usr/share/doc/deets/examples
	$(INSTALL_FILE) example.cosmo debian/deets/usr/share/doc/deets/examples
	gzip -9f debian/deets/usr/share/doc/deets/changelog.Debian
	gzip -9f debian/deets/usr/share/man/man1/luau.1
	strip --remove-section=.comment --remove-section=.note debian/deets/usr/bin/luau
	dpkg-shlibdeps -Tdebian/deets.substvars debian/deets/usr/bin/luau
	$(INSTALL_DIR) debian/deets/DEBIAN
	dpkg-gencontrol -ldebian/changelog -Tdebian/deets.substvars -Pdebian/deets
	cd debian/deets && find * -type f ! -regex '^DEBIAN/.*' -print0 | xargs -r0 md5sum > DEBIAN/md5sums
	chown -R root:root debian/deets
	chmod -R a+rX debian/deets
	dpkg --build debian/deets ..

clean:
	$(checkdir)
	if test -d obj && cd obj && test -f Makefile; then $(MAKE) distclean; fi
	test ! -f Makefile || $(MAKE) distclean
	-rm -f $$(find . -name "*~") core debian/*ubstvars \
		stamp-build stamp-configure debian/files \
		config.cache config.status config.status.lineno
	-rm -rf debian/deets config.cache obj \
                autom4te.cache

binary-indep:

define checkdir
	test -f debian/rules
endef

checkroot:
	$(checkdir)
	test root = "`whoami`"

.PHONY: binary binary-arch binary-indep build clean configure install checkroot
