#!/bin/sh

service pgbouncer stop

set -e

# prepare cleanup at exit
CLEAN_FILES="/etc/pgbouncer/pgbouncer.ini /etc/pgbouncer/userlist.txt"
cleanup () {
	if [ "$PGVERSION" ]; then
		pg_ctlcluster $PGVERSION regress stop -m f || :
		pg_dropcluster $PGVERSION regress || :
	fi
	service pgbouncer stop || :
	for f in $CLEAN_FILES; do
		test -f $f.adt-save && mv -f $f.adt-save $f
	done
	rm -f output
}
trap cleanup 0 2 3 15

# create PostgreSQL cluster
if ! pg_lsclusters -h | grep -q '5432 online'; then
	PGVERSION=$(/usr/share/postgresql-common/supported-versions | tail -n1)
	pg_createcluster $PGVERSION regress -p 5432 --start
fi

# set up minimal pgbouncer config
sed -i.adt-save -e '/\[databases\]/ apostgres =' /etc/pgbouncer/pgbouncer.ini
test -e /etc/pgbouncer/userlist.txt &&
	cp -a /etc/pgbouncer/userlist.txt /etc/pgbouncer/userlist.txt.adt-save
echo "\"postgres\" \"postgres\"" >> /etc/pgbouncer/userlist.txt

# start pgbouncer and test connection
service pgbouncer start
echo "Trying simple SELECT ..."
result=$(PGPASSWORD=postgres psql -p 6432 -d postgres -U postgres -c "SELECT 1+2" -tA)
echo "$result"
[ "$result" = "3" ]
echo "Result OK"
