#!/bin/sh -eu
CNAME="lxc-test-$(uuidgen)"

# Check arguments
if [ "${1:-}" = "" ] || [ "${2:-}" = "" ] || [ "${3:-}" = "" ] || [ "${4:-}" = "" ] || [ "${5:-}" = "" ]; then
    echo "Usage: ${0} <arch> <async-api> <repository> <branch> <commit>"
    exit 1
fi

ARCH=${1}
shift
ASYNC_API=${1}
shift
REPO=${1}
shift
BRANCH=${1}
shift
COMMIT=${1}
shift

cleanup() {
    incus delete --force "${CNAME}"
}

trap cleanup EXIT HUP INT TERM

# Create the container
incus copy "cache-lxc-${ARCH}" "${CNAME}"

# Add loop-control for this test
incus config device add "${CNAME}" loop-control unix-char source=/dev/loop-control

# Mark as privileged
incus config set "${CNAME}" security.privileged true

# Allow all mounts
incus config set "${CNAME}" raw.apparmor mount,

# Start the container
incus start "${CNAME}"

set -x

(
cat << EOF
#!/bin/sh
# Wait for network
while :; do
    ping -W1 -c1 linuxcontainers.org >/dev/null 2>&1 && break
    sleep 1
done

set -eux

# Create build directories
mkdir -p /build/source

# Get the source
git clone "${REPO}" -b "${BRANCH}" /build/source
cd /build/source
git fetch "${REPO}" "+refs/pull/*:refs/remotes/origin/pr/*"
git checkout "${COMMIT}"

# Build LXC
cd /build/source/
if [ -e autogen.sh ]; then
    ./autogen.sh
    CC=clang ./configure --disable-python3 --enable-tests --prefix=/usr/ --sysconfdir=/etc/ --localstatedir=/var/
    make
    make install
else
    WANT_IO_URING="-Dio-uring-event-loop=false"
    if [ "${ASYNC_API}" = "io_uring" ]; then
        WANT_IO_URING="-Dio-uring-event-loop=true"
    fi
    CC=clang CC_LD=gold meson setup build/ "\${WANT_IO_URING}" -Dtests=true -Dpam-cgroup=true -Dprefix=/usr/ -Dsysconfdir=/etc/ -Dlocalstatedir=/var/
    ninja -C build
    ninja -C build install
fi

# Prepare for tests
(
cat << EOG
network:
  version: 2
  ethernets:
    eth0:
      accept-ra: false
      dhcp4: false
      dhcp6: false
  bridges:
    lxcbr0:
      accept-ra: true
      dhcp4: true
      dhcp6: true
      interfaces:
        - eth0
EOG
) > /etc/netplan/10-lxc.yaml

netplan generate
netplan apply

# Workaround for AppArmor bug (https://gitlab.com/apparmor/apparmor/-/merge_requests/1112)
sed -i "s/lxd-/incus-/g" /lib/apparmor/rc.apparmor.functions

systemctl restart apparmor

# Setup pyhton test
if [ -e /build/source/src/python-lxc/examples/api_test.py ]; then
    mkdir -p /usr/share/doc/python3-lxc/examples/
    cp -p /build/source/src/python-lxc/examples/api_test.py /usr/share/doc/python3-lxc/examples/
    gzip -9 /usr/share/doc/python3-lxc/examples/api_test.py
fi

# Setup tmpfs for the tests
mount -t tmpfs tmpfs /home
mkdir -p /var/lib/lxc
mount -t tmpfs tmpfs /var/lib/lxc

# Run testsuite
/build/lxc-exercise

exit 0
EOF
) | incus file push - "${CNAME}/root/build.sh" --mode=755
incus file push -p deps/lxc-exercise "${CNAME}/build/lxc-exercise"
incus exec "${CNAME}" -- /root/build.sh "$@"
