#!/usr/bin/make -f

POD2MAN=pod2man --center "Debian PostgreSQL infrastructure" -r "Debian"
POD1PROGS=pg_wrapper pg_lsclusters
POD1PROGS_POD=pg_buildext pg_virtualenv
POD8PROGS=pg_ctlcluster pg_createcluster pg_dropcluster pg_upgradecluster pg_updatedicts

VERSION := $(shell dpkg-parsechangelog | awk '/^Version:/ { print $$2 }')
ifneq ($(findstring bpo,$(VERSION)),)
	FLAVOR := debian-backports
else ifneq ($(findstring pgdg,$(VERSION)),)
	FLAVOR := pgdg
else
	FLAVOR := default
endif
SUPPORTED_VERSIONS := $(shell PG_SUPPORTED_VERSIONS="$(FLAVOR)" debian/supported-versions)
DEFAULT_VER := $(lastword $(SUPPORTED_VERSIONS))

%:
	dh "$@"

version_info:
	@echo "### Building postgresql-common flavor $(FLAVOR)"
	@echo "### Supported PostgreSQL versions: $(SUPPORTED_VERSIONS) (default version: $(DEFAULT_VER))"
build build-arch build-indep: version_info

override_dh_install:
	dh_install
	install -m 644 -D debian/postgresql-common.sysctl debian/postgresql-common/etc/sysctl.d/30-postgresql-shm.conf
	for p in $(POD1PROGS); do $(POD2MAN) --quotes=none --section 1 $$p > $$p.1 || exit 1; done
	for p in $(POD1PROGS_POD); do $(POD2MAN) --quotes=none --section 1 $$p.pod > $$p.1 || exit 1; done
	for p in $(POD8PROGS); do $(POD2MAN) --quotes=none --section 8 $$p > $$p.8 || exit 1; done
ifneq ($(FLAVOR),default)
	/bin/echo -e "# See /usr/share/postgresql-common/supported-versions for documentation of this file\n$(FLAVOR)" > debian/postgresql-client-common/etc/postgresql-common/supported_versions
endif

override_dh_installinit:
	dh_installinit --name=postgresql -u'defaults 19 21' -r

override_dh_gencontrol:
	dh_gencontrol -ppostgresql-server-dev-all -- -Vserver-dev-all-depends="$(foreach v,$(SUPPORTED_VERSIONS),postgresql-server-dev-$v,)"

	# the versionless metapackages need to have version numbers which match
	# the server version, not the p-common version
	dh_gencontrol -ppostgresql -ppostgresql-client -ppostgresql-doc -ppostgresql-contrib  -- \
		-Vdefault-version="$(DEFAULT_VER)" -v'$(DEFAULT_VER)+$${source:Version}'

ifeq ($(FLAVOR),pgdg)
	# for apt.postgresql.org builds, pull in the repository key package
	dh_gencontrol -ppostgresql-client-common -- -Vpgdg:Depends="pgdg-keyring"
endif

	dh_gencontrol --remaining-packages

override_dh_clean:
	dh_clean
	for p in $(POD1PROGS) $(POD1PROGS_POD); do rm -f $$p.1 || exit 1; done
	for p in $(POD8PROGS); do rm -f $$p.8 || exit 1; done
