#!/bin/sh

set -eux

# link shape loader/dumper to where the testsuite expects them
for prg in shp2pgsql pgsql2shp; do
  test -x loader/$prg || ln -s /usr/bin/$prg loader/$prg
done

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

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

# Skip tests on problematic architectures
ARCH="$(dpkg-architecture -qDEB_BUILD_ARCH)"

if [ "${ARCH}" = "armel" ] || [ "${ARCH}" = "armhf" ] || [ "${ARCH}" = "mips" ] || [ "${ARCH}" = "mips64el" ] || [ "${ARCH}" = "mipsel" ] || [ "${ARCH}" = "s390x" ] || [ "${ARCH}" = "alpha" ] || [ "${ARCH}" = "hppa" ] || [ "${ARCH}" = "hurd-i386" ] || [ "${ARCH}" = "kfreebsd-i386" ] || [ "${ARCH}" = "powerpc" ] || [ "${ARCH}" = "ppc64" ] || [ "${ARCH}" = "sparc64" ]; then
  echo "Skipping tests on problematic architectures"
  exit 77
fi

# clean up on exit
trap "rm -rf /tmp/pgis_reg" EXIT

# run the regression tests
for v in $(pg_buildext installed-versions); do
  pg_virtualenv -v $v <<-EOF
	set -eux
	make -C regress/core -f Makefile.in check PERL=perl RUNTESTFLAGS="--extension --verbose" POSTGIS_GEOS_VERSION=$POSTGIS_GEOS_VERSION
	make -C sfcgal/regress -f Makefile.in check PERL=perl RUNTESTFLAGS="--extension --verbose" HAVE_SFCGAL=yes
	EOF
done
