#!/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
    echo "Starting lxd-installer.socket now that LXD snap was removed"
    systemctl start lxd-installer.socket
fi

echo "Report list of installed snaps:"
snap list

echo "Trigger the on-demand installation and check stderr for user notification"
lxc list 2>&1 > /dev/null | grep -xF "Installing LXD snap, please be patient."

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

TRACKING="$(snap info lxd | awk '/^tracking: / {print $2}')"
EXPECTS="5.21/stable/ubuntu-${VERSION_ID}"
if [ "${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}"
fi

if [ -z "${TRACKING}" ] || [ -z "${EXPECTS}" ]; then
    echo "lxd-installer could not determine which channel to install LXD from" >&2
    exit 1
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
