#!/bin/sh

pkgver=$1
pkgver_major=${pkgver%%.*}
default_ver=$(pg_versions get-default 2>/dev/null) || true

# If this package is not set as the default PostgreSQL version (see
# pg_versions), let it go.
[ "$default_ver" = "$pkgver_major" ] || exit 0

# If this package ('postgresql<majorver>') has been installed explicitly, i.e.
# not via 'postgresql' provider or as a dependency, the user is apparently
# uninstalling it intentionally, so let it go.
grep -Fqx "postgresql$pkgver_major" /etc/apk/world 2>/dev/null && exit 0

data_dir=$(
	. /etc/conf.d/postgresql 2>/dev/null
	echo "${data_dir:-"/var/lib/postgresql/$pkgver_major/data"}"
)
# If data_dir for this version does not exist or is empty, let it go.
[ -f "$data_dir"/PG_VERSION ] || exit 0


cat >&2 <<EOF
*
* You are uninstalling your default PostgreSQL version ($default_ver) which seems to be
* in use! If it's *not* intentional and you want to preserve this version,
* install it explicitly: \`apk add postgresql$default_ver\`.
*
* Please note that to upgrade your cluster to a new major version using
* pg_upgrade(1), you must have both the old and new versions installed.
*
EOF

exit 1
