#!/bin/sh -e

DIR=$1
if test -z "$DIR"; then
    DIR=$(mktemp -d)
else
    DIR=$(readlink -f "$DIR")
fi
if test -e "$DIR"/postmaster.pid; then
  pg_ctl -D "$DIR" stop
fi
if test -d "$DIR"; then
  rm -r "$DIR"
fi
initdb --auth-local=peer -N "$DIR" -U "$(id -u -n)"
(echo "listen_addresses=''"
echo "unix_socket_directories='$DIR'"
echo "fsync=off"
echo "full_page_writes=off") >> "$DIR"/postgresql.conf

LOGDIR="$DIR/log"
LOGFILE="${LOGFILE:-"$LOGDIR/postgresql-openqa-test.log"}"
echo "PostgreSQL logs will be stored in $LOGFILE."

mkdir -p "$LOGDIR"
pg_ctl -D "$DIR" -l "$LOGFILE" start
createdb -h "$DIR" openqa_test

echo "Now export TEST_PG like:"
echo ""
echo "  export TEST_PG='DBI:Pg:dbname=openqa_test;host=$DIR'"
echo ""
echo " and if you don't need it anymore, use pg_ctl -D $DIR stop"
