#!/bin/sh

set -exu

SRC="$(pwd)"

# change to temporary directory to not interfere with the source
cd "$AUTOPKGTEST_TMP"

# coverage.sh expects the scripts to be in the current directory
# we copy make_mirror.sh instead of symlinking it because we are going to patch
# it
cp -a "$SRC/make_mirror.sh" make_mirror.sh
ln -s "$SRC/run_qemu.sh" run_qemu.sh

# All of this is a temporary workaround until #909637 is fixed and we can use
# fakechroot instead

# make_mirror.sh runs ./mmdebstrap with --mode=unshare. Since we don't want to
# require machine isolation, we create a small wrapper script which is suid
# root and calls the *installed* mmdebstrap with --mode=root
# We need to make use of the suid bit because we run coverage.sh as a normal
# user but need to run mmdebstrap as root.
# Shell scripts cannot have the suid bit, so we need to compile a small C
# program.

cat << 'END' > ./suidexec.c
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char* argv[]) {
	char **args = (char **)malloc(sizeof(char*)*argc+2);
	args[0] = "mmdebstrap";
	for (int i = 1; i < argc; ++i) {
		args[i] = argv[i];
	}
	args[argc] = "--mode=root";
	args[argc+1] = (char *)NULL;
	setuid(0);
	execv("/usr/bin/mmdebstrap", args);
}
END
gcc ./suidexec.c -o ./mmdebstrap

chmod u+s,a+x ./mmdebstrap

mkdir ./shared
chown $AUTOPKGTEST_NORMAL_USER ./shared

# wrap umount because /proc refuses to cleanly unmount under schroot if the
# packages binfmt-support and qemu-user-static are installed in debootstrap
# variant
mkdir ./bin
cat << 'END' > ./bin/umount
#!/bin/sh
exec /bin/umount --lazy "$@"
END
chmod +x ./bin/umount

if [ ! -e /dev/kvm ]; then
	mknod --mode=660 /dev/kvm c 10 232
	chown root:kvm /dev/kvm
fi

adduser $AUTOPKGTEST_NORMAL_USER kvm

# place the installed mmdebstrap into the current directory so that coverage.sh
# can copy it into the shared directory
cp /usr/bin/mmdebstrap ./shared

# now run the script
# we set PATH so that the umount wrapper is used
# we set CMD so that Devel::Cover is not used
runuser -u $AUTOPKGTEST_NORMAL_USER -- env CMD=./mmdebstrap PATH="$AUTOPKGTEST_TMP/bin:/bin:/usr/bin" "$SRC/coverage.sh"
