#!/bin/sh

set -eux

PGDATA="$(pg_conftool -s show data_directory)"
trap "cat $PGDATA/*.log || :" EXIT

if [ "${DESTDIR:-}" ]; then
  # pljava-1.2.3.jar
  set -- $DESTDIR/usr/share/postgresql/$PGVERSION/pljava/pljava-?.*.jar
  PLJAR="$1"
  # pljava-api-1.2.3.jar
  set -- $DESTDIR/usr/share/postgresql/$PGVERSION/pljava/pljava-api-?.*.jar
  PLAPIJAR="$1"
  psql -c "ALTER USER $PGUSER SET pljava.module_path = '$PLJAR:$PLAPIJAR'"
  # use policy file allowing access outside of the default codebase directory
  POLICY="$PWD/debian/tests/pljava.policy"
  psql -c "ALTER USER $PGUSER SET pljava.policy_urls = '\"file://$POLICY\"'"
fi

set -- ${DESTDIR:-}/usr/share/postgresql/$PGVERSION/pljava/pljava-examples-*.jar
EXJAR="$1"

psql -c "ALTER USER $PGUSER SET check_function_bodies = off"
psql -c "CREATE EXTENSION pljava"
psql -c "SELECT sqlj.install_jar('file:$EXJAR', 'examples', true)"
psql -c "SELECT sqlj.set_classpath('javatest', 'examples')"
psql -c "SELECT sqlj.get_classpath('javatest')"
psql -c "SELECT javatest.java_addone(1)"
