#!/usr/bin/make -f

PERL   ?= /usr/bin/perl
PACKAGE = $(shell dh_listpackages)
TMP     = $(CURDIR)/debian/$(PACKAGE)

export DEB_BUILD_MAINT_OPTIONS=hardening=+all
include /usr/share/dpkg/buildtools.mk
include /usr/share/dpkg/architecture.mk
PERLVER := $(shell perl -MConfig -e 'print $$Config{version}')
ARCHLIB := $(shell perl -I/usr/lib/$(DEB_HOST_MULTIARCH)/perl/cross-config-$(PERLVER) -MConfig -e 'print $$Config{vendorarch}')

%:
	dh  $@

override_dh_auto_build:
	# The following is pasted from an interactive session, to better
	# understand what is echoed to Makefile.PL:
	#
	# Add commands to compile the package here
	#
	# Following echo answers the questions below.
	# What do you want to build?
	# 1) Interface to Ace socket server and local databases (pure Perl)
	# 2) The above plus XS optimizations (requires C compiler)
	# 3) The above plus RPC server interface (requires C compiler)
	#
	# Enter your choice:  [1]
	# Do you want to install Ace::Browser?  [n]
	# Directory for the site-specific configuration files (~username ok): [/usr/local/apache/conf/ace]
	# Directory does not exist.  Shall I create it for you? [y]
	# Directory for the acebrowser CGI scripts (~username ok): [/usr/local/apache/cgi-bin/ace]
	# Directory does not exist.  Shall I create it for you? [y]
	# Directory for the acebrowser HTML files and images (~username ok): [/usr/local/apache/htdocs/ace]
	perl -e "print qq(3\ny\n$(CURDIR)/debian/$(PACKAGE)/etc/libace-perl\ny\n$(CURDIR)/debian/$(PACKAGE)/usr/lib/cgi-bin\ny\n$(CURDIR)/debian/$(PACKAGE)/usr/share/$(PACKAGE))" \
	| $(PERL) \
		Makefile.PL \
		INSTALLDIRS=vendor \
		CC=$(CC) \
		LD=$(CC) \
		INSTALLVENDORARCH=$(ARCHLIB) \
		INSTALLARCHLIB=$(ARCHLIB)
	dh_auto_build --buildsystem=makefile -- \
		OPTIMIZE="$(CFLAGS)" \
		LD_RUN_PATH="" \
		OTHERLDFLAGS="$(LDFLAGS)"

override_dh_auto_test:
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	@ echo W: tests are disabled due to requiring internet access.
endif

execute_before_dh_clean:
	if [ -f Makefile ] \
	; then $(MAKE) realclean \
	; fi
	$(RM) --recursive docs/Ace

override_dh_auto_install:
	# Adjust architecture dependent information from README.Debian.
	sed -i 's/@DEB_HOST_MULTIARCH@/$(DEB_HOST_MULTIARCH)/g' \
		debian/README.Debian
	# Add commands to install the package into $(TMP)
	$(MAKE) install DESTDIR=$(TMP) PREFIX=/usr
	mv $(TMP)/usr/bin/ace.pl $(TMP)/usr/bin/ace
	# Manpage is somehow empty, so it is replaced by the manually
	# edited debian/ace.1.
	rm -f $(TMP)/usr/share/man/man1/ace.pl.1p
	if [ -d $(TMP)/usr/share/perl5 ] \
	; then rmdir --ignore-fail-on-non-empty --parents --verbose \
		$(TMP)/usr/share/perl5 \
	; fi

# Ensure the use of the system interpreter.
execute_after_dh_installexamples:
	sed -i 's?#!/usr/local/bin/perl?#!/usr/bin/perl?' \
		$(TMP)/usr/share/doc/$(PACKAGE)/examples/*.pl
