#!/usr/bin/make -f

# See debhelper(7) (uncomment to enable).
# Output every command that modifies files on the build system.
#export DH_VERBOSE = 1


# See FEATURE AREAS in dpkg-buildflags(1).
#export DEB_BUILD_MAINT_OPTIONS = hardening=+all

# See ENVIRONMENT in dpkg-buildflags(1).
# Package maintainers to append CFLAGS.
#export DEB_CFLAGS_MAINT_APPEND  = -Wall -pedantic
# Package maintainers to append LDFLAGS.
#export DEB_LDFLAGS_MAINT_APPEND = -Wl,--as-needed


%:
	dh $@


# dh_make generated override targets.
# This is an example for Cmake (see <https://bugs.debian.org/641051>).
#override_dh_auto_configure:
#	dh_auto_configure -- \
#	-DCMAKE_LIBRARY_PATH=$(DEB_HOST_MULTIARCH)

override_dh_auto_configure:
	# Backup existing conf-* files to prevent permanent modification
	for file in conf-*; do \
		if [ -f "$$file" ] && [ ! -f "$$file.bak" ]; then \
			cp "$$file" "$$file.bak"; \
		fi; \
	done

	echo /usr/bin > conf-bin
	echo /usr/share/man > conf-man
	echo gcc $(shell dpkg-buildflags --get CFLAGS) > conf-cc
	echo gcc -s -rdynamic $(shell dpkg-buildflags --get LDFLAGS) > conf-ld
	echo /usr/include/bglibs > conf-bgincs
	echo /usr/lib/$(shell dpkg-architecture -qDEB_HOST_MULTIARCH)/bglibs > conf-bglibs
	# Adjust mysql paths if needed via multiarch
	sed -i -e 's@/usr/lib/mysql@/usr/lib/$(shell dpkg-architecture -qDEB_HOST_MULTIARCH)@g' Makefile

override_dh_auto_build:
	dh_auto_build -- all mysql

override_dh_auto_install:
	mkdir -p debian/qmail-autoresponder/usr/bin
	mkdir -p debian/qmail-autoresponder/usr/share/man/man1
	mkdir -p debian/qmail-autoresponder-mysql/usr/bin
	
	# Install directly using package prefixes or move after standard install
	$(MAKE) install install_prefix=$(CURDIR)/debian/qmail-autoresponder
	
	# Move the mysql binary to its specific package layout
	if [ -f debian/qmail-autoresponder/usr/bin/qmail-autoresponder-mysql ]; then \
		mv debian/qmail-autoresponder/usr/bin/qmail-autoresponder-mysql debian/qmail-autoresponder-mysql/usr/bin/; \
	fi

# 4. Clean up, restore configuration files from backups, and wipe created ones
override_dh_auto_clean:
	dh_auto_clean
	# Restore backed up configurations, or remove them if they were generated fresh
	for file in conf-*; do \
		if echo "$$file" | grep -q '\.bak$$'; then \
			continue; \
		fi; \
		if [ -f "$$file.bak" ]; then \
			mv "$$file.bak" "$$file"; \
		else \
			rm -f "$$file"; \
		fi; \
	done
