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

set -eu

suite=testing
arch="$(dpkg --print-architecture)"

scratch="$(mktemp -d -p /var/lib/schroot/unpack)"

if ! sbuild-createchroot \
    --arch="$arch" \
    --make-sbuild-tarball "/srv/$suite-$arch.tar" \
    "$suite" "$scratch"
then
    echo "SKIP: Unable to create chroot $suite-$arch-sbuild"
    rm -fr "$scratch"
    exit 77
fi

export AUTOPKGTEST_TEST_SCHROOT="testing-$arch-sbuild"

if ! schroot -d / -c "$AUTOPKGTEST_TEST_SCHROOT" -- true
then
    echo "SKIP: Unable to enter chroot $suite-$arch-sbuild"
    exit 77
fi

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.
annotate-output ./tests/autopkgtest SchrootRunner

if [ -n "${AUTOPKGTEST_NORMAL_USER-}" ]; then
    usermod -a -G sbuild "$AUTOPKGTEST_NORMAL_USER"
    runuser -u "$AUTOPKGTEST_NORMAL_USER" -- annotate-output ./tests/autopkgtest \
        SchrootRunner.test_dsc_build_needed_success \
        SchrootRunner.test_setup_commands \
        SchrootRunner.test_tree_norestrictions_nobuild_success \
        SchrootRunner.test_user \
        SchrootRunner.test_user_needs_root \
        ${NULL+}
fi
