#!/bin/bash

set -e

[ -n "$1" ] && SID=$1 || SID=1

PGDATA=`pwd`/tmpdb$SID

PGROOT=`pwd`/tmp_install
export PGDATA

export PATH="$PGROOT/usr/local/pgsql/bin:$PATH"
export LD_LIBRARY_PATH="$PGROOT/usr/local/pgsql/lib"

pg_ctl -w -t 5 stop -m immediate >/dev/null || true

[ -d "$PGDATA" ] && rm -rf "$PGDATA"
LC_ALL='en_US.UTF-8' initdb --username=postgres >initdb$SID.log 2>&1 || { echo "initdb failed"; exit 1; }

export PGPORT=$((15431 + 10#$SID))
echo "
port = $PGPORT

autovacuum = on
autovacuum_naptime = 1s
autovacuum_vacuum_threshold = 1
autovacuum_analyze_threshold = 1
log_autovacuum_min_duration = 0

log_line_prefix = '%m [%d] [%p:%l][%b] %q[%a][%v:%x] '
log_connections = true
log_disconnections = true
log_statement = all
log_min_messages = DEBUG3

fsync = off
" >> $PGDATA/postgresql.auto.conf

[ -f server$SID.log ] && rm server$SID.log
pg_ctl -l server$SID.log start

export PGDATABASE=postgres
export PGUSER=postgres

[ -f psql-$SID.log ] && rm psql-$SID.log
res=0
for ((i=1; i<=100; i++)); do
echo "iteration $i"

cat << 'EOF' | timeout 60 psql >>psql-$SID.log || { res=1; echo "hanged on iteration $i"; break; }
SELECT format('CREATE TABLE t%s (a int, b text);', g) FROM generate_series(1, 80) g
\gexec

SELECT format('DROP TABLE t%s;', g) FROM generate_series(1, 80) g
\gexec
EOF
wait
done

[ $res = 0 ] && pg_ctl -w -t 120 stop >/dev/null
exit $res
