#!/usr/bin/make -f

#export DH_VERBOSE=1
export DH_COMPAT=2

# Parse DEB_BUILD_OPTIONS as in the policy manual, chapter 11
CFLAGS = -Wall -g
ifneq (,$(findstring noopt,$(DEB_BUILD_OPTIONS)))
CFLAGS += -O0
else
CFLAGS += -O2
endif
export CFLAGS

# Work around outdated configure.guess (still need an up-to-date configure.sub)
export DEB_HOST_GNU_TYPE  ?= $(shell dpkg-architecture -qDEB_HOST_GNU_TYPE)
export DEB_BUILD_GNU_TYPE ?= $(shell dpkg-architecture -qDEB_BUILD_GNU_TYPE)


PWD=$(shell pwd)

# upstream provides new version simply as patch, so change the source version to:
PATCHEDVERSION := $(strip $(shell dpkg-parsechangelog | awk -F: '/^Version:/ {print $$NF}' | sed -e s/-/-a-/))

build: patch build-stamp
build-stamp:
	dh_testdir

	mkdir build
	cd build && ../configure \
		--build=$(DEB_BUILD_GNU_TYPE) --host=$(DEB_HOST_GNU_TYPE) \
		--prefix=/usr --enable-threads || ( cat config.log; exit 1; )
	$(MAKE) -C build

	touch build-stamp

clean: unpatch
	dh_testdir
	dh_testroot
	-rm -f build-stamp install-stamp

	-rm -rf build
	-rm -f docs/mikmod.info

	dh_clean

install:
	dh_testdir
	dh_testroot
	dh_clean -k
	dh_installdirs

	$(MAKE) -C build install DESTDIR=$(PWD)/debian/tmp

	touch install-stamp

patch: patch-stamp
patch-stamp:
	set -e; \
	if [ -d debian/patches ]; then \
	  for patch in `ls debian/patches/*`; do \
	    patch -p1 <$$patch; \
	  done; \
	fi

	touch patch-stamp

unpatch:
	set -e; \
	if [ -f patch-stamp ]; then \
	  for patch in `ls -r debian/patches/*`; do \
	    patch -R -p1 <$$patch; \
	  done; \
	fi
	
	-rm -f patch-stamp

binary-indep: build install
# Nothing to do (anymore)

binary-arch: build install
	dh_testdir -a
	dh_testroot -a
	dh_movefiles -a
	dh_installdocs -a
	dh_installman -a
	dh_installinfo -a docs/mikmod.info*
	dh_installchangelogs -a NEWS
	dh_strip -a
	dh_compress -a
	dh_fixperms -a
	dh_makeshlibs -a
	dh_installdeb -a
	dh_shlibdeps -a
# upstream provides new version simply as patch, so change the source version to:
	dh_gencontrol -a -u"-v$(PATCHEDVERSION) -VBinary-Version=$(PATCHEDVERSION)"
	dh_md5sums -a
	dh_builddeb -a

binary: binary-indep binary-arch
.PHONY: binary binary-arch binary-indep build clean install patch unpatch
