#!/bin/sh

# autopkgtest script for pgbouncer: starts a pgbouncer instance and connects
# through it to a postgres server running on port 5432

# autopkgtest's TMPDIR is not readable for postgres
unset TMPDIR

if [ -z "$WRAPPED" ]; then
	WRAPPED=1 pg_virtualenv $0 "$@"
	exit
fi

/etc/init.d/pgbouncer stop

set -e

# prepare cleanup at exit
CLEAN_FILES="/etc/pgbouncer/pgbouncer.ini /etc/pgbouncer/userlist.txt /etc/default/pgbouncer"
cleanup () {
	/etc/init.d/pgbouncer stop || :
	rm -f /etc/pgbouncer/userlist.txt output
	for f in $CLEAN_FILES; do
		test -f $f.adt-save && mv -f $f.adt-save $f
	done
}
trap cleanup 0 2 3 15

# 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 "\"$PGUSER\" \"$PGPASSWORD\"" >> /etc/pgbouncer/userlist.txt
sed -i.adt-save -e 's/START=0/START=1/' /etc/default/pgbouncer

# start pgbouncer and test connection
/etc/init.d/pgbouncer start
echo "Trying simple SELECT ..."
result=$(psql -p 6432 -d 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 -d postgres -tA > output
cat output
[ "$(cat output)" = "7
11" ]
echo "Result OK"
