#!/bin/sh

set -eux

SOURCE=$(dpkg-parsechangelog -SSource)
MAJOR=${SOURCE#*-}

make -C contrib/spi PGXS=$(/usr/lib/postgresql/$MAJOR/bin/pg_config --pgxs) USE_PGXS=1

cd src/test/regress

# compile regress.so
make -f ../../../debian/tests/Makefile.regress PG_CONFIG=/usr/lib/postgresql/$MAJOR/bin/pg_config
ln -sf libregress.so regress.so

# tell regression files that regress.so is not installed
sed -i -e "s:@libdir@/regress:$PWD/regress:" input/*.source output/*.source

# create tablespace and results directories
rm -rf testtablespace results regression.*
mkdir testtablespace results
if [ "$(id -u)" = "0" ]; then
  chown postgres: testtablespace results
  chmod -R go+rX .
fi

# this tests is missing some CONTEXT from plpgsql functions
sed -i -e 's/plpgsql//' parallel_schedule
# TODO: testing fails with permission problems, disable most tests for now
sed -i -e '/create_function_1/,$ d' parallel_schedule

# run the regression tests
if ! pg_virtualenv -v $MAJOR \
  /usr/lib/postgresql/$MAJOR/lib/pgxs/src/test/regress/pg_regress --psqldir="/usr/lib/postgresql/$MAJOR/bin" --schedule=parallel_schedule --load-language=plpgsql; then
    cat regression.diffs
    exit 1
fi
