#!/bin/sh
set -eux
lxd_channel() {
    track=""

    # pull from the latest LXD LTS: $LTS/stable/ubuntu-$VERSION
    # with major version assigned and opened prior to Ubuntu release
    # shellcheck disable=SC1091
    [ -r /etc/os-release ] && . /etc/os-release
    case "${VERSION_ID:-""}" in
      "25.10")
        track="5.21";;
      "25.04")
        track="5.21";;
      "24.10")
        track="5.21";;
      "24.04")
        track="5.21";;
      "22.04")
        track="5.0";;
      "20.04")
        track="4.0";;
      *)
        ;;
    esac

    if [ -n "${track}" ] && [ -n "${VERSION_ID:-""}" ]; then
      echo "${track}/stable/ubuntu-${VERSION_ID}"
    else
      echo ""
    fi
}

# Only do the snap installation when invoked with the lxd-installer-service name.
# This allows sourcing the script without triggering the snap installation.
if [ "${0##*/}" = "lxd-installer-service" ]; then
    # Wait for snapd to be seeded
    snap wait system seed.loaded || true

    CHANNEL="$(lxd_channel)"
    if [ -z "${CHANNEL}" ]; then
        echo "Unable to determine the LXD LTS channel, aborting" >&2
        exit 1
    fi

    for i in 1 2 3; do
        snap install lxd --channel="${CHANNEL}" 1>&2 && break
        echo "Unable to install the LXD snap, retrying (${i}/3)" >&2
        sleep "${i}"
    done

    echo 1
fi
