#!/bin/sh

set -eux

# link shape loader/dumper to where the testsuite expects them
PRGS="loader/shp2pgsql loader/pgsql2shp raster/loader/raster2pgsql"
for prg in $PRGS; do
  test -x $prg || ln -s /usr/bin/$(basename $prg) $prg
done

# delete test directory before possibly switching user
rm -rf /tmp/pgis_reg

# make Makefile.in believe that we have completed staged-install
for file in regress/staged-install-raster regress/staged-install-topology regress/staged-install; do
  test -f $file || touch $file
done

# re-start ourselves as nobody since PG can't run as root
if [ "$(id -un)" = "root" ]; then
  exec su nobody -s /bin/sh "$0" "$@"
fi

# Makefile.in needs some variables from ./configure, set the most important ones here
POSTGIS_GEOS_VERSION="$(dpkg-query -f '${Version}' --show 'libgeos-*.*' | cut -c 1,3)"

# clean up on exit
trap "rm -rf /tmp/pgis_reg $PRGS regress/staged-install* || :" EXIT

# run the regression tests
for v in $(pg_buildext supported-versions); do
  case $v in
    9*) POSTGIS_PGSQL_VERSION=$(echo $v | tr -d .) ;;
    *) POSTGIS_PGSQL_VERSION="${v}0" ;;
  esac
  pg_virtualenv -v $v \
    make -C regress -f Makefile.in check \
      PERL=perl \
      RUNTESTFLAGS="--extension --verbose" \
      POSTGIS_PGSQL_VERSION=$POSTGIS_PGSQL_VERSION \
      POSTGIS_GEOS_VERSION=$POSTGIS_GEOS_VERSION \
      PG_CONFIG=/usr/lib/postgresql/$v/bin/pg_config \
      HAVE_SFCGAL=yes
done
