#!/bin/sh

set -e

# Runtime variables
export PGPOOLCONF=$(mktemp)
export PGPOOLPORT=9999

# If we didn't already run inside a pg virtual environment
# start ourself inside one.
if [ -z "$PGVIRTUAL" ]; then
	# when running under adt-run, allow "postgres" to access the temporary
	# directories
	if [ -n "$ADTTMP" ]; then
		chown -R postgres:postgres "$ADTTMP"
		unset TMPDIR
	fi
	/etc/init.d/pgpool2 stop
	_SYSTEMCTL_SKIP_REDIRECT=1 /etc/init.d/pgpool2 stop
	PGVIRTUAL=1 exec pg_virtualenv "$0" "$@"
fi

# Generate locale needed
. /usr/share/postgresql-common/pgcommon.sh
locale_gen en_US.UTF-8 UTF-8

cleanup () {
	set +e
	echo "Clean up environment"
	rm $PGPOOLCONF
	/usr/sbin/pgpool -m fast stop 2>&1
}
trap cleanup 0 2 3 15

cd src/test/regression/tests/005.jdbc/

cat >> $PGPOOLCONF <<EOF
#ADT#
listen_addresses = '127.0.0.1'
port = $PGPOOLPORT
backend_hostname0 = '$PGHOST'
backend_port0 = $PGPORT
pool_passwd = ''
EOF
cat $PGPOOLCONF
echo

cat > pgpool.properties <<EOF
pgpooltest.host=$PGHOST
pgpooltest.port=$PGPOOLPORT
pgpooltest.user=$PGUSER
pgpooltest.password=$PGPASSWORD
pgpooltest.dbname=postgres
pgpooltest.options=
pgpooltest.tests=autocommit batch column lock select update insert
EOF
# no need to restore this file, we just unlink it in debian/rules
cat pgpool.properties
echo

/usr/sbin/pgpool -n -f $PGPOOLCONF 2>&1 &
sleep 5
echo

echo "Prepare environment"
# We need to append IF EXISTS to all DROP TABLE statements,
# otherwise the test will fail.
sed 's/DROP\ TABLE\ [^I]/DROP\ TABLE\ IF\ EXISTS\ /' prepare.sql | \
    psql -v ON_ERROR_STOP=1 -p $PGPOOLPORT 2>&1
echo

echo "Run JDBC-test"
export LC_ALL=en_US.UTF-8 # Hoge.java has utf-8 comments
chmod +x run.sh
PGPORT=$PGPOOLPORT CLASSPATH=/usr/share/java/postgresql.jar:. ./run.sh
echo
