#!/bin/sh

/etc/init.d/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
	/etc/init.d/pgbouncer stop || :
	for f in $CLEAN_FILES; do
		test -f $f.adt-save && mv -f $f.adt-save $f
	done
	rm -f /etc/pgbouncer/userlist.txt output
}
trap cleanup 0 2 3 15

# create PostgreSQL cluster
if [ -z "$(pg_lsclusters -h)" ]; then
	PGVERSION=$(/usr/share/postgresql-common/supported-versions | tail -n1)
	pg_createcluster $PGVERSION regress --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
/etc/init.d/pgbouncer start
echo "Trying simple SELECT ..."
result=$(psql -p 6432 -d postgres -U postgres -c "SELECT 1+2" -tA)
echo "$result"
[ "$result" = "3" ]
echo "Result OK"

echo "Trying online restart ..."
(
	echo "SELECT 3+4;"
	/etc/init.d/pgbouncer restart > /dev/null
	sleep 1
	echo "SELECT 5+6;"
) | psql -p 6432 -U postgres -d postgres -tA > output
cat output
[ "$(cat output)" = "7
11" ]
echo "Result OK"
