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

set -eu

if dpkg-vendor --is ubuntu; then
    mirror="http://archive.ubuntu.com/ubuntu"
    suite=$(ubuntu-distro-info --latest)
    components="main universe"
else
    # default to Debian
    mirror="http://deb.debian.org/debian"
    suite=testing
    components="main"
fi

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=apt \
    "$suite" \
    "$scratch/rootfs.tar" \
    "deb $mirror $suite $components" \
    "deb-src $mirror $suite $components" \
    ${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"
