#!/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"

JAVA_VERSION=$(java --version | head -n1 | grep -Eo '[0-9]+' | head -n1)
if [ "$JAVA_VERSION" -ge 20 ]; then
  # tell Java 20+ that we use the Java security architecture (https://github.com/tada/pljava/wiki/JEP-411)
  psql -c "ALTER USER $PGUSER SET pljava.vmoptions = '-Djava.security.manager=allow'"
fi

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)"
