#!/bin/sh
set -e
testuser="testrunner"

TEST_LIST="$1"
if [ -z "$TEST_LIST" ]; then
    TEST_LIST_PARAM=""
    echo "No list given, will run all tests."
else
    TEST_LIST_PARAM="-T $TEST_LIST"
    echo "Running tests: $TEST_LIST"
fi

grep -q "^KillUserProcesses=yes$" /etc/systemd/logind.conf || echo "KillUserProcesses=yes" >>/etc/systemd/logind.conf
systemctl restart systemd-logind.service

if testuid=$(id -u $testuser 2>/dev/null) ; then
    systemctl stop user-$testuid.slice
else
    useradd -m ${testuser}
fi

echo "${testuser} ALL=(root:root) NOPASSWD:ALL" >/etc/sudoers.d/zfs-${testuser}

modprobe zfs
zfs unmount -a -f
sleep 1
zpool export -a

losetup -D
systemctl stop zfs-zed.service nfs-blkmap.service nfs-server.service nfs-client.target nfs-idmapd.service nfs-mountd.service || true
rm -f /etc/hostid

# We delibrately use a persistent temporary directory here
# to prevent the tests from using too much memory.
testdir="$(mktemp -d --tmpdir=/var/tmp --suffix=-zfs-tests)"
chown ${testuser}:${testuser} $testdir
chmod 0775 $testdir

setpriv --reset-env --init-groups --reuid ${testuser} --regid ${testuser} /usr/share/zfs/zfs-tests.sh -vKR -s 3G $TEST_LIST_PARAM -d $testdir
