#!/bin/sh
#
alias message="echo >&2"
error () { message "$@"; exit 2; }

test -e db &&
	error "./db exists. Looks as if we are already initialized..."

PGC="$(test -x "$1" && realpath "$1" || which pg_config)"
test -x "$PGC" ||
	error "$PGC is not executable, please specify the path to pg_config"
alias pgc="$PGC"

message "Testing against $PGC: $(pgc --version).."

mkdir db output
cat >db/conf <<EOF
unset PGDATABASE PGUSER PGSERVICE PGSSLMODE PGREQUIRESSL PGCONNECT_TIMEOUT
alias message="echo >&2"
error () { message "ERROR: " "\$@"; exit 2; }

export PGDATA="$(realpath db/data)"
export PGDATABASE="regress"
export PGPORT=65432

pgbin="$(pgc --bindir)"
pglib="$(pgc --libdir)"
pgpkglib="$(pgc --pkglibdir)"
pgversion="$(pgc --version)"

alias initdb="message 'initializing database...'; \$pgbin/initdb"
alias pgctl="\$pgbin/pg_ctl 2>&- >&-"
alias psql="\$pgbin/psql 2>&1 -q -a -X"
alias pgstart='message "starting database...";
	pgctl start -w -l "$(realpath db/logfile)"'
alias pgstop='message "stopping database..."; pgctl stop -w -m fast'
EOF

. db/conf
initdb 2>&1 -E UNICODE >db/init.log ||
	error "failed to initialize test database, see db/init.log for reason"
cat >db/data/postgresql.conf <<EOF
max_connections = 20
shared_buffers = 500
syslog = 0
silent_mode = false
client_min_messages = debug1
log_error_verbosity = default
EOF
pgstart ||
	error "failed to start database"
trap pgstop EXIT
psql -d template1 << EOF
CREATE FUNCTION plpy_handler()
RETURNS LANGUAGE_HANDLER LANGUAGE C
AS '\$libdir/plpy.so', 'pl_handler';

CREATE FUNCTION plpy_validator(oid)
RETURNS VOID LANGUAGE C
AS '\$libdir/plpy.so', 'pl_validator';

CREATE FUNCTION plpy_finalizer()
RETURNS VOID LANGUAGE C
AS '\$libdir/plpy.so', 'pl_finalize';

CREATE LANGUAGE plpy
	HANDLER plpy_handler
	VALIDATOR plpy_validator;

CREATE FUNCTION py()
RETURNS VOID LANGUAGE plpy
AS 'from code import InteractiveConsole as ic; ic(locals=locals()).interact()';
EOF
test $? -ne 0 && exit 1
sleep 2
createdb
