#!/usr/bin/make -f
# -*- makefile -*-
# Sample debian/rules that uses debhelper.
# This file was originally written by Joey Hess and Craig Small.
# As a special exception, when this file is copied by dh-make into a
# dh-make output file, you may use that output file without restriction.
# This special exception was added by Craig Small in version 0.37 of dh-make.

# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1


# These are used for cross-compiling and for saving the configure script
# from having to guess our platform (since we know it already)
DEB_HOST_GNU_TYPE   ?= $(shell dpkg-architecture -qDEB_HOST_GNU_TYPE)
DEB_BUILD_GNU_TYPE  ?= $(shell dpkg-architecture -qDEB_BUILD_GNU_TYPE)

ifeq (,$(findstring nostrip,$(DEB_BUILD_OPTIONS)))
    CONFIG_FLAGS += --enable-debug
endif

%:
	dh $@

override_dh_auto_configure:
	# Add here commands to configure the package.
	CFLAGS="$(CFLAGS) -Wl,-z,defs" 
	dh_auto_configure -- \
			--with-ssh \
			--with-genders \
			--with-readline \
			--without-rsh \
			--prefix=/usr \
			--mandir=\$${prefix}/share/man \
                        --infodir=\$${prefix}/share/info \
                        $(CONFIG_FLAGS)

MODULE_DIRS := src/modules/.libs tests/test-modules/.libs
override_dh_auto_test:
	# pdsh will refuse to load modules in subdirs not owned by either
	# the building user or root, which causes many tests to fail on
	# the builders (see #1022365). We workaround that by copying
	# the module dirs to a temp directory and symlinking them into
	# the build tree.

	# dh_auto_test will do this, but we need to build them first
	# so we can copy them to the tempdir
	$(MAKE) -C tests/test-modules check

	# Save a copy of the module dirs to restore later
	tar -c $(MODULE_DIRS) > debian/module-dirs.tar

	# Now replace module dirs with symlinks to tempdir counterparts
	# and run the tests.
	set -e; \
	tmpdir=`mktemp -d`; \
	(cd $$tmpdir && tar xv) < debian/module-dirs.tar; \
	rm -rf $(MODULE_DIRS); \
	for dir in $(MODULE_DIRS); do \
		ln -s $$tmpdir/$$dir $$dir; \
	done; \
	dh_auto_test; \
	rm -rf $$tmpdir

	# Restore the module directories (replacing the symlinks)
	tar xv < debian/module-dirs.tar

override_dh_auto_install:
	dh_auto_install
	# Clean up directory
	rm -f $(CURDIR)/debian/pdsh/usr/lib/**/pdsh/*.a
	rm -f $(CURDIR)/debian/pdsh/usr/lib/**/pdsh/*.la

	# Install pdsh script
	mv $(CURDIR)/debian/pdsh/usr/bin/pdsh $(CURDIR)/debian/pdsh/usr/bin/pdsh.bin
	cp $(CURDIR)/debian/pdsh.script $(CURDIR)/debian/pdsh/usr/bin/pdsh
	chmod 755 $(CURDIR)/debian/pdsh/usr/bin/pdsh
	rm -f $(CURDIR)/debian/pdsh/usr/bin/pdcp
	cp $(CURDIR)/debian/pdcp.script $(CURDIR)/debian/pdsh/usr/bin/pdcp
	chmod 755 $(CURDIR)/debian/pdsh/usr/bin/pdcp
	rm -f $(CURDIR)/debian/pdsh/usr/bin/rpdcp
	cp $(CURDIR)/debian/rpdcp.script $(CURDIR)/debian/pdsh/usr/bin/rpdcp
	chmod 755 $(CURDIR)/debian/pdsh/usr/bin/rpdcp

override_dh_auto_clean:
	rm -f debian/module-dirs.tar
	find . -name .libs -type l -exec rm {} \;
	dh_auto_clean
