#!/bin/sh
#
# start_postgres.sh - starts an instance of postgres before
# auto_installing and running do_mysql's test suite. It is inspired by
# debian/test_mysql.sh from libdbi-drivers source package and 
# t/dbdpg_test_setup.pl from libdbd-pg-perl.



set -evx

MYTEMP_DIR=`mktemp -d`

SCRIPT_USER=`stat -c %U $0`
ME=`whoami`

BINDIR=`pg_config --bindir`


INFO=`${BINDIR}/initdb -D --locale=C -E UTF-8 ${MYTEMP_DIR} 2>&1 || true`
#if we are root, we need to find another user to run the server
if echo $INFO | grep "root"; then
	FOUNDUSER=0

	USER_LIST="$ME $SCRIPT_USER postgres"

	for x in $USER_LIST; do
		if [ "$x" = "root" ] ; then
			continue
		fi
		TEST_USER=$x
		chown -vR $TEST_USER $MYTEMP_DIR || break
		SU_USER=$x
		FOUNDUSER=$((FOUNDUSER + 1))
                ( cd $MYTEMP_DIR ; INFO=`su -m $SU_USER -c "${BINDIR}/initdb --locale=C -E UTF-8 -D ${MYTEMP_DIR} 2>&1"` ) || continue
                [ $? -eq 0 ] && break
	done
	if [ "$SU_USER" = "" ]; then
		TEST_USER=`echo $INFO | sed -e "s/owned by user (\.+)/$1/"`
	fi
fi

# environment variables for ruby-dataobjects-postgres test suite
export DO_POSTGRES_USER=${SU_USER}
#export DO_POSTGRES_PASS=
export DO_POSTGRES_DBNAME=do_test
export DO_POSTGRES_DATABASE=/do_test


# start postgres server
if [ ! "$SU_USER" = "" ]; then
	su -m $SU_USER -c "${BINDIR}/pg_ctl -D ${MYTEMP_DIR} -o\"-h '' -k ${MYTEMP_DIR}\" -l /tmp/pgres.log start"
else
	${BINDIR}/postgres -D ${MYTEMP_DIR} -k ${MYTEMP_DIR} &
fi
attempts=0
while ! [ -e ${MYTEMP_DIR}/postmaster.pid ] ; do
	attempts=$((attempts+1))
	if [ "${attempts}" -gt 10 ] ; then
		echo "skipping test, postgres pid file was not created after 30 seconds"
		exit 0
	fi
	sleep 3
	echo `date`: retrying...
done
:
# Set the env. var so that pgsql client doesn't use networking

export PGHOST=${MYTEMP_DIR}


#create test database
if [ "$SU_USER" = "" ]; then
	createdb -e ${DO_POSTGRES_DBNAME}
else
	su -m $SU_USER -c "createdb -e ${DO_POSTGRES_DBNAME}"
fi

dh_auto_install
ecode=$?
#
## Kill the postgress process and wait of it to shutdown
if [ "$SU_USER" = "" ]; then
	dropdb -e ${DO_POSTGRES_DBNAME}
	$BINDIR/pg_ctl stop -D ${MYTEMP_DIR}
else
	su -m $SU_USER -c "dropdb -e ${DO_POSTGRES_DBNAME}"
	su -m $SU_USER -c "$BINDIR/pg_ctl stop -D ${MYTEMP_DIR}"
fi
rm -rf $MYTEMP_DIR
exit $ecode
