#!/bin/sh

set -e

if [ "$(uname -s)" = 'GNU' ] ; then
    echo "Sorry, testsuite requires unshare(1). GNU Hurd patches welcome."
    exit
fi

if ischroot ; then
    echo "Sorry, testsuite uses unshare(2) which is not permitted within a chroot."
    exit
fi

cd "$(dirname "$0")"

if [ $# -eq 0 ] ; then
    # Run all if none specified
    set -- $(find . -name test -executable -exec dirname '{}' ';')
fi

export DEB_GREP_ENABLE_STRAY_BACKSLASH_WARN=1 # Ensure #1019326 is visible
export DEBIAN_FRONTEND=noninteractive
export UCF_TEST_TARGET=/tmp
export UCF_TEST_BINDIR="${UCF_TEST_BINDIR=../../}"

trap 'echo "Testsuite: ${i:-0}/$# tests completed"' EXIT

for tdir do
    echo "Running $tdir" >&2
    unshare -rmw "$tdir" sh  <<'EOF' || { echo "WARNING: unshare(1) failed, skipping test" >&2 && continue ; }
set -e
mount -t tmpfs tmpfs /var/cache/debconf
if [ -d /var/lib/ucf ] ; then
 mount -t tmpfs tmpfs /var/lib/ucf
else
 udir=$(mktemp -d)
 wdir=$(mktemp -d)
 trap 'rm -rf $udir $wdir' EXIT
 mount -t overlay none -o lowerdir=/var/lib,upperdir=$udir,workdir=$wdir /var/lib
 mkdir -p /var/lib/ucf
fi
mount -t tmpfs tmpfs /tmp
./test | diff -u expected/output -
diff -ur expected/target $UCF_TEST_TARGET
diff -ur expected/state /var/lib/ucf
EOF
    i=$((i+1))
done
