#!/usr/bin/make -f

include /usr/share/cdbs/1/rules/debhelper.mk
include /usr/share/cdbs/1/class/autotools.mk

LDFLAGS+=-Wl,--as-needed

DEB_CONFIGURE_EXTRA_FLAGS := --enable-doxygen \
 --enable-static=no
DEB_DH_INSTALL_SOURCEDIR = debian/tmp
DB2MAN = /usr/share/sgml/docbook/stylesheet/xsl/nwalsh/manpages/docbook.xsl
XP = xsltproc -''-nonet
SOVERSION = 8
SUBSTFILES = debian/libmtp$(SOVERSION).docs	\
	debian/libmtp$(SOVERSION).install	\
	debian/libmtp$(SOVERSION).preinst	\
	debian/libmtp$(SOVERSION).postinst
UDEVFILES = 45-libmtp$(SOVERSION).rules 20-libmtp$(SOVERSION).fdi
DISTRIBUTION = $(shell lsb_release -i | cut -f2 -d':')

debdir = $(CURDIR)/debian
debver = $(shell perl -ne '/([\d.-]+)/;print "$$1"; last' \
		debian/changelog)

# Replace SOVERSION string in debian/ files
libmtp$(SOVERSION).%: libmtp.%.in
	sed "s/@SOVERSION@/$(SOVERSION)/g" < $<	> $@
%: %.in
	sed "s/@SOVERSION@/$(SOVERSION)/g" < $<	> $@

makebuilddir/libmtp$(SOVERSION):: $(SUBSTFILES) debian/control
	# Save file modified by configure
	test -e src/gphoto2-endian.h-orig \
		|| cp src/gphoto2-endian.h src/gphoto2-endian.h-orig

install/libmtp-doc::
	# Rename some man files and remove others
	chmod +x debian/sanitize-manpage.pl
	( cd doc/man/man3/ ;						\
	  rm -f _* ;							\
	  for i in $$(ls *.3 | grep -v ^mtp_) ; do			\
		../../../debian/sanitize-manpage.pl < $$i > mtp_$$i ;	\
	  done )

binary-install/libmtp$(SOVERSION)::
	if [ ${DISTRIBUTION} = 'Ubuntu' ]; then \
		mkdir -p $(debdir)/libmtp$(SOVERSION)/usr/share/apport/package-hooks/ ;\
		install -m 0644 $(debdir)/apport/* \
			$(debdir)/libmtp$(SOVERSION)/usr/share/apport/package-hooks/ ; \
	fi

build/libmtp$(SOVERSION)::
	# Fix mode of udev lifting script
	chmod +x libmtp.sh
	# Rename udev files
	for f in $(UDEVFILES) ; do				\
		cp libmtp.$${f#*.} $$f ;			\
	done

binary-predeb/libmtp$(SOVERSION)::
ifeq (linux,$(DEB_HOST_ARCH_OS))
	echo "udev=udev" >> debian/libmtp$(SOVERSION).substvars
endif
	# Remove rpath from the library
	chrpath --delete $(debdir)/libmtp$(SOVERSION)/usr/lib/libmtp.so.*.*

mtp-tools.1: debian/mtp-tools.dbk
	# Build and install the man page for mtp-tools
	$(XP) $(DB2MAN) $<

build/mtp-tools:: mtp-tools.1

binary-predeb/mtp-tools::
	# Remove rpath from programs
	chrpath --delete $(debdir)/mtp-tools/usr/bin/*

clean::
	rm -f mtp-tools.1 $(SUBSTFILES) $(UDEVFILES)
	# Restore original file
	test ! -e src/gphoto2-endian.h-orig \
		|| mv src/gphoto2-endian.h-orig src/gphoto2-endian.h
