#!/usr/bin/make -f

include /usr/share/postgresql-common/pgxs_debian_control.mk

override_dh_pgxs_test:
	rm -rf /tmp/pg-repack-tablespace
	mkdir /tmp/pg-repack-tablespace
	+PATH=$(firstword $(wildcard $(CURDIR)/debian/postgresql-*-repack/usr/lib/postgresql/18/bin)):$(PATH) \
		pg_buildext -i'--auth=trust' installcheck . regress postgresql-%v-repack
	rm -rf /tmp/pg-repack-tablespace

override_dh_auto_build:

override_dh_auto_test:
	# nothing to do here, see debian/tests/* instead

override_dh_installdocs:
	dh_installdocs --all doc/*

override_dh_auto_install:
	sed -i 's|\$$(libpq)|-lpgcommon -lpgport \$$(libpq)|g' bin/Makefile
	+pg_buildext loop percona-postgresql-%v-repack
	# Install an alternative for /usr/bin/pg_repack. We could wrap this
	# using pg_wrapper, but it doesn't matter which binary gets used (it
	# figures out the server version by itself), so we just use the one for
	# the newest server version.
	set -ex; \
	for v in $(shell pg_buildext supported-versions); do \
		i=$$(echo $$v | tr -d .); \
		echo "update-alternatives --install /usr/bin/pg_repack pg_repack /usr/lib/postgresql/$$v/bin/pg_repack $$i" >> debian/percona-postgresql-$$v-repack.postinst.debhelper; \
		echo "update-alternatives --remove pg_repack /usr/lib/postgresql/$$v/bin/pg_repack" >> debian/percona-postgresql-$$v-repack.prerm.debhelper; \
	done

%:
	dh $@

override_dh_builddeb:
	dh_builddeb -- -Zgzip
	# Ubuntu's dh_builddeb renames auto-dbgsym .deb -> .ddeb (so they would be
	# routed to ddebs.ubuntu.com) and records the renamed name in debian/files.
	# OBS's apt-repo publisher only indexes *.deb, so undo both: rename the
	# files on disk AND rewrite debian/files, otherwise dpkg-genbuildinfo /
	# dpkg-genchanges fail to fstat the .ddeb names listed there. No-op on
	# Debian.
	if ls ../*-dbgsym_*.ddeb >/dev/null 2>&1; then \
	  for f in ../*-dbgsym_*.ddeb; do \
	    mv -v "$$f" "$${f%.ddeb}.deb"; \
	  done; \
	  sed -i 's/\(-dbgsym_[^ ]*\)\.ddeb/\1.deb/g' debian/files; \
	fi
