#!/bin/bash -ex

# This script runs the integration tests on an already configured LXD machine
# where the tests are run LXD in LXD.  i.e. an LXD container is spawned, pylxd
# is copied into the container, and then the container runs the integration
# tests.

# This script is NOT used by the CI system, but for people to run integration
# tests on their own computers where they don't want the integration test to
# mess with their setup.

DIR="$(realpath "$(dirname "${BASH_SOURCE[0]}")")"

declare -A RELEASE_IMAGES=(
    [jammy]="22.04"
    [noble]="24.04"
)

function run_tests {
    local target="$1"
    local image="${RELEASE_IMAGES[$target]}"
    local container_name="pylxd-${target}-$$"
    local container_image="ubuntu-daily:${image}"
    echo "Running ${image} integration tests"

    lxc launch --ephemeral "$container_image" "$container_name" -c security.nesting=true

    lxc exec "$container_name" -- mkdir -p /opt/pylxd
    tar -cf - --exclude-vcs --exclude-vcs-ignores -C "${DIR}/.." . | lxc exec "$container_name" -- tar -xf - -C /opt/pylxd

    lxc exec "$container_name" -- cloud-init status --long --wait
    lxc exec "$container_name" --cwd /opt/pylxd -- integration/run-integration-tests
    lxc delete --force "$container_name"
}

# Make sure unprivileged userns clone is enabled otherwise security.nesting=true
# won't work.
if [ "$(cat /proc/sys/kernel/unprivileged_userns_clone)" -eq 0 ]; then
    echo "unpriviliged userns clone disabled, unable to run tests" >&2
    exit 1
fi

declare -a images
if [ $# -gt 0 ]; then
    images=("$@")
else
    images=("${!RELEASE_IMAGES[@]}")
fi
for image in "${images[@]}"; do
    run_tests "$image"
done
