#!/bin/sh

set -eu

if [ -z "${PGVIRTUAL:-}" ]; then
	PGVIRTUAL=1 exec pg_virtualenv "$0" "$@"
fi

# alternate directory for odbc(inst).ini
export ODBCSYSINI=$(mktemp -d -t odbcsysini.XXXXXX)

cleanup () {
	set +e
	rm -rf $ODBCSYSINI
}

trap cleanup 0 2 3 15

odbcinst -i -d -f debian/odbcinst.ini.template
sed -i \
	-e "s!psqlodbca.so!$PWD/build/A/.libs/psqlodbca.so!" \
	-e "s!psqlodbcw.so!$PWD/build/W/.libs/psqlodbcw.so!" \
	$ODBCSYSINI/odbcinst.ini

cat >> $ODBCSYSINI/odbc.ini <<EOT
[ANSI]
Description         = PostgreSQL
Driver              = PostgreSQL ANSI
Trace               = Yes
TraceFile           = psqlodbc.log
Database            = $PGDATABASE
Servername          = $PGHOST
UserName            = $PGUSER
Password            = $PGPASSWORD
Port                = ${PGPORT:-}
ReadOnly            = No
RowVersioning       = No
ShowSystemTables    = No
ShowOidColumn       = No
FakeOidIndex        = No
ConnSettings        =
BI = float8
Debug = Yes

[Unicode]
Description         = PostgreSQL
Driver              = PostgreSQL Unicode
Trace               = Yes
TraceFile           = psqlodbc.log
Database            = $PGDATABASE
Servername          = $PGHOST
UserName            = $PGUSER
Password            = $PGPASSWORD
Port                = ${PGPORT:-}
ReadOnly            = No
RowVersioning       = No
ShowSystemTables    = No
ShowOidColumn       = No
FakeOidIndex        = No
ConnSettings        =
BI = float8
Debug = Yes
EOT

QUERY="CREATE TABLE a (t text, i int);
INSERT INTO a VALUES ('test', 2*3*7*101);
SELECT i FROM a WHERE t = 'test';
DROP TABLE a;"
RESULT="4242"

echo "unixodbc ANSI test"
echo "$QUERY" | isql -b ANSI | grep "$RESULT" || EXIT=$?
# sometimes the logs are in /tmp, ignore errors for now
cat *.log 2>&1 || :
rm -f *.log
echo

echo "unixodbc Unicode test"
echo "$QUERY" | iusql -b Unicode | grep "$RESULT" || EXIT=$?
cat *.log 2>&1 || :
rm -f *.log
echo

echo "Running test suite"
cd test
sed -i -e 's/^Port/#Port/' odbc.ini
echo "#ADT#" >> odbc.ini
echo "Port = ${PGPORT:-5432}" >> odbc.ini
if ! make installcheck; then
	EXIT=1
	echo "regression.diffs:"
	cat "regression.diffs" || :
fi
sed -i -e 's/^#Port/Port/' -e '/#ADT#/,$d' odbc.ini

exit ${EXIT:-0}
