#!/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 "Source lxd-installer-service and check that no snap is installed"
. /usr/share/lxd-installer/lxd-installer-service

echo "Test lxd_channel function from imported script"
CHANNEL="$(lxd_channel)"

echo "Check the returned channel is not empty"
if [ -z "${CHANNEL}" ]; then
    echo "lxd-installer could not obtain the LXD snap channel to use from lxd_channel function" >&2
    exit 1
fi

echo "Check the returned channel is a stable one for Ubuntu ${VERSION_ID}"
if ! echo "${CHANNEL}" | grep -xE "[0-9]+\.[0-9]+/stable/ubuntu-${VERSION_ID}"; then
    echo "lxd-installer did not obtain a valid LXD snap channel to use from lxd_channel function" >&2
    exit 1
fi

echo "Report list of installed snaps:"
snap list

echo "Make sure LXD snap was not installed"
if snap list lxd; then
    echo "lxd-installer sourcing lxd-installer-service should not have installed LXD snap" >&2
    exit 1
fi
