#!/bin/sh
set -eu

if ! dpkg-vendor --is ubuntu; then
    echo "SKIP: LXD test requires an Ubuntu host"
    exit 77
fi

arch=$(dpkg --print-architecture)

if [ -z "${AUTOPKGTEST_NORMAL_USER-}" ]; then
    echo "Skipping test because it requires an AUTOPKGTEST_NORMAL_USER"
    exit 77
fi

# snapd and the LXD snap are installed at runtime rather than declared as test
# dependencies: autopkgtest installs those before the vendor check above.
if ! command -v snap >/dev/null; then
    DEBIAN_FRONTEND=noninteractive apt-get -q --yes install snapd
fi

snap wait system seed.loaded
snap install lxd
export PATH="$PATH:/snap/bin"

if [ -z "${AUTOPKGTEST_TEST_UNINSTALLED-}" ]; then
    export AUTOPKGTEST_TEST_INSTALLED=yes
    build_lxd=autopkgtest-build-lxd
else
    build_lxd=tools/autopkgtest-build-lxd
fi

# Detect LXD API extensions
lxd_extension() {
    lxc info | grep -q "^\- ${1}$"
}

lxd waitready
lxd init --minimal
lxc profile set default security.nesting true
lxd init --dump

adduser "$AUTOPKGTEST_NORMAL_USER" lxd

[ -n "${http_proxy:-}" ] && lxc config set core.proxy_http "${http_proxy}"
[ -n "${https_proxy:-}" ] && lxc config set core.proxy_https "${https_proxy}"

# work around broken PTMU in Canonical Scalingstack
iptables -t mangle -A FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu

# buildd images are very light
runuser -u "$AUTOPKGTEST_NORMAL_USER" -- lxc remote add buildd https://cloud-images.ubuntu.com/buildd/daily --protocol simplestreams

remote=buildd
vendor=ubuntu
suite=$(ubuntu-distro-info --lts)
image="$remote:$suite/$arch"

runuser -u "$AUTOPKGTEST_NORMAL_USER" -- \
"$build_lxd" "$image"

exec annotate-output \
runuser -u "$AUTOPKGTEST_NORMAL_USER" -- \
env \
    AUTOPKGTEST_TEST_INSTALLED="${AUTOPKGTEST_TEST_INSTALLED-}" \
    AUTOPKGTEST_TEST_UNINSTALLED="${AUTOPKGTEST_TEST_UNINSTALLED-}" \
    AUTOPKGTEST_TEST_LXD="autopkgtest/$vendor/$suite/$arch" \
./tests/autopkgtest LxdRunner
