#!/bin/sh

set -eu

if [ -z "${PGVIRTUAL:-}" ]; then
	# adt sets TMPDIR to a path that's not readable for postgres, breaking pg_virtualenv
	unset TMPDIR

	for v in $(pg_buildext supported-versions); do
		PGVIRTUAL=1 pg_virtualenv -v $v "$0" "$@"
	done
	exit
fi

export ODBCINI=$(mktemp -t odbcini.XXXXXX)

cleanup () {
	set +e
	rm -f $ODBCINI
}

trap cleanup 0 2 3 15

cat > $ODBCINI <<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
grep ^ psqlodbc*.log /tmp/psqlodb*.log 2>&1 || :
rm -f psqlodbc*.log /tmp/psqlodb*.log
echo

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

exit ${EXIT:-0}
