#!/usr/bin/make -f

#export DH_VERBOSE=1

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

MAKEFILE = $(firstword $(MAKEFILE_LIST))
DEBIAN_DIR = $(dir $(MAKEFILE))
SOURCE_DIR = $(DEBIAN_DIR)/..

DEB_VERSION = $(shell dpkg-parsechangelog -l$(DEBIAN_DIR)/changelog | grep ^Version | cut -d" " -f2)
DEB_SOURCE_NAME = $(shell dpkg-parsechangelog -l$(DEBIAN_DIR)/changelog | grep ^Source | cut -d" " -f2)
VERSION = $(shell echo $(DEB_VERSION) | cut -d"-" -f1 | sed 's/+ds.*//')

CFLAGS = -Wall -g

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

configure: configure-stamp
configure-stamp:
	dh_testdir
	
	libtoolize
	intltoolize --force
	aclocal
	autoconf
	automake --add-missing --copy
	
	MCS=/usr/bin/mono-csc \
	CFLAGS="$(CFLAGS)" ./configure --host=$(DEB_HOST_GNU_TYPE) \
	  --build=$(DEB_BUILD_GNU_TYPE) --prefix=/usr --sysconfdir=/etc \
	  --mandir=\$${prefix}/share/man --infodir=\$${prefix}/share/info \
	  --disable-schemas-install
	# --enable-dbus=yes
	
	touch $@

build: build-stamp
build-stamp: configure-stamp
	dh_testdir
	$(MAKE)
	touch $@

build-arch: build
build-indep: build

clean:
	dh_testdir
	dh_testroot
	[ ! -f Makefile ] || $(MAKE) distclean
	# upstream's make clean is unclean
	rm -f src/gfax.exe.mdb
	find . -name "Makefile.in" -delete
	dh_clean config.log config.status config.sub config.guess configure ltmain.sh

install: build
	dh_testdir
	dh_testroot
	dh_prep 
	dh_installdirs
	$(MAKE) install DESTDIR=$(CURDIR)/debian/gfax

binary-indep: build install
	dh_testdir
	dh_testroot
	dh_installchangelogs -i ChangeLog
	dh_installdocs -i
	dh_installexamples -i
	dh_installmenu -i
	dh_installman -i
	dh_gconf -i
	dh_link -i
	dh_strip -i
	dh_clistrip -i
	dh_compress -i
	dh_fixperms -i -Xvar/spool/gfax
	dh_clifixperms -i
	dh_installdeb -i
	dh_shlibdeps -i
	dh_clideps -i
	dh_gencontrol -i
	dh_md5sums -i
	dh_builddeb -i

binary-arch:

binary: binary-indep binary-arch

get-orig-source:
	[ -d ../tarballs ] || mkdir ../tarballs
	uscan \
		--package $(DEB_SOURCE_NAME) \
		--watchfile $(DEBIAN_DIR)/watch \
		--upstream-version $(VERSION) \
		--download-version $(VERSION) \
		--destdir . \
		--force-download \
		--rename \
		--repack
	if [ -d $(DEB_SOURCE_NAME)-$(VERSION) ]; then \
		echo "$(DEB_SOURCE_NAME)-$(VERSION) is in the way, bailing out!"; \
		exit 1; \
	fi
	tar -xzf $(DEB_SOURCE_NAME)_$(VERSION).orig.tar.gz
	rm $(DEB_SOURCE_NAME)_$(VERSION).orig.tar.gz
	rm -fr $(DEB_SOURCE_NAME)-$(VERSION)/debian/
	tar --mtime=@1255820400 -cf ../tarballs/$(DEB_SOURCE_NAME)_$(VERSION)+ds.orig.tar $(DEB_SOURCE_NAME)-$(VERSION)
	gzip -9fn ../tarballs/$(DEB_SOURCE_NAME)_$(VERSION)+ds.orig.tar
	rm -r $(DEB_SOURCE_NAME)-$(VERSION)

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