#!/bin/sh

set -eux

. /etc/os-release
echo "Executing test on ${NAME:-Unknown} version ${VERSION_ID:-n/a}"

echo "Check which lxd-installer version we have installed"
dpkg -l | grep -wF lxd-installer

echo "Make sure LXD's snap is not seeded in the current image"
if snap list lxd; then
    echo "Removing seeded LXD snap"
    snap remove --purge lxd
fi

echo "Report list of installed snaps:"
snap list

echo "Trigger the on-demand installation"
lxc list

echo "Check which version of LXD was installed"
snap list lxd

TRACKING="$(snap info lxd | awk '/^tracking: / {print $2}')"
if [ "${VERSION_ID:-}" = "24.04" ]; then
    EXPECTS="5.21/stable/ubuntu-${VERSION_ID}"
elif [ "${VERSION_ID:-}" = "22.04" ]; then
    EXPECTS="5.0/stable/ubuntu-${VERSION_ID}"
elif [ "${VERSION_ID:-}" = "20.04" ]; then
    EXPECTS="4.0/stable/ubuntu-${VERSION_ID}"
else
    EXPECTS="latest/stable"
fi

echo "Verify it matches the expected version"
if [ "${TRACKING}" = "${EXPECTS}" ]; then
    echo "lxd-installer installed LXD from the right track (${EXPECTS})"
else
    echo "lxd-installer did not install LXD from the expected track (${TRACKING} != ${EXPECTS})" >&2
    exit 1
fi

