#!/bin/sh
# Copyright 2022 Jochen Sprickerhof
# Copyright 2022 Simon McVittie
# SPDX-License-Identifier: GPL-2.0-or-later

set -eu

# Skip in Ubuntu for now because of LP: #2049529
if dpkg-vendor --is ubuntu; then
    echo "SKIP: adduser and useradd are broken in Ubuntu, see LP: #2049529"
    exit 77
fi

suite=testing
scratch="$(mktemp -d)"

# Skip the test if unprivileged namespaces are restricted, see:
# https://gitlab.com/apparmor/apparmor/-/wikis/unprivileged_userns_restriction.
# This is the default in (some?) Ubuntu systems.
if [ "$(sysctl -ne kernel.apparmor_restrict_unprivileged_userns)" = 1 ]; then
    echo "SKIP: unprivileged namespaces are restricted (kernel.apparmor_restrict_unprivileged_userns=1)"
    exit 77
fi

# --skip=cleanup/apt/lists: expected by tests, alternatively autopkgtest -U
# --keyring is explicitly set so that it works on Ubuntu too
if ! mmdebstrap \
    --include=eatmydata \
    --mode=unshare \
    --skip=cleanup/apt/lists \
    --variant=buildd \
    --keyring=/usr/share/keyrings/debian-archive-keyring.gpg \
    "$suite" \
    "$scratch/rootfs.tar" \
    "deb http://deb.debian.org/debian $suite main" \
    "deb-src http://deb.debian.org/debian $suite main" \
    ${NULL+}
then
    echo "SKIP: Unable to create rootfs tarball"
    rm -fr "$scratch"
    exit 77
fi

export AUTOPKGTEST_TEST_UNSHARE="$scratch/rootfs.tar"

if [ -z "${AUTOPKGTEST_TEST_UNINSTALLED-}" ]; then
    export AUTOPKGTEST_TEST_INSTALLED=yes
fi

# Wrapping the test in annotate-output helps to distinguish the output of
# the autopkgtest that is running these tests from the output of the
# autopkgtest that is under test, which would otherwise be really confusing.
e=0
annotate-output ./tests/autopkgtest UnshareRunner || e=1
rm -fr "$scratch"
exit "$e"
