#!/bin/sh

# some tests insist on /var/run/postgresql/, so run as root

set -e

cleanup () {
	for f in test/sql/*.sql.orig; do
		test -f $f || continue
		mv $f ${f%.orig}
	done
}
trap "cleanup" EXIT HUP INT QUIT PIPE TERM

for v in $(pg_buildext supported-versions); do
	case $v in
		8*|9.0) make sql/plproxy.sql
			;;
		*)	# we want to test the installed extension, so don't source from the build tree
			sed -i.orig 's/\\i.*plproxy\.sql/CREATE EXTENSION plproxy;/' test/sql/*.sql
			;;
	esac

	# AUTOPKGTEST_TMP is not writeable by any user except root, but
	# we want to use it for storing the Postgres socket
	# Set PG_CLUSTER_CONF_ROOT, because although we are running in a
	# network namespace (so we can reuse the default port),
	# pg_virtualenv/pg_createcluster looks at the configured
	# databases on the filesystem
	# Set the socket directory because we are to re-use the port and
	# there can be conflicts in the normal socket directory
	if ! chmod o+w $AUTOPKGTEST_TMP && \
		PG_CLUSTER_CONF_ROOT=$AUTOPKGTEST_TMP \
		PG_CONFIG=/usr/lib/postgresql/$v/bin/pg_config \
		unshare -inu pg_virtualenv -c "-p 5432 --locale C -s $AUTOPKGTEST_TMP" -i '--auth trust' -v $v \
		make -f $PWD/Makefile installcheck; then \
			head -n 500 regression.diffs
			exit 1
	fi

	cleanup
done
