#!/bin/sh
SNAP_BIN="/snap/bin/${0##*/}"
if [ ! -f "${SNAP_BIN}" ]; then
    if [ ! -e "/run/lxd-installer.socket" ]; then
        echo -n "Waiting for lxd-installer.socket to start" >&2
        for _ in $(seq 10); do
            sleep 1
            [ -e "/run/lxd-installer.socket" ] && break
            echo -n . >&2
        done
        echo " done" >&2
    fi

    if [ ! -w "/run/lxd-installer.socket" ]; then
      echo "Unable to trigger the installation of the LXD snap." >&2
      echo "Please make sure you're a member of the 'lxd' system group." >&2
      exit 1
    fi

    echo "Installing LXD snap, please be patient." >&2
    python3 -c 'import socket; s=socket.socket(socket.AF_UNIX); s.connect("/run/lxd-installer.socket"); s.send(b"x"); s.recv(1)' >&2

    for _ in $(seq 90); do
      sleep 1
      [ -x "${SNAP_BIN}" ] && break
    done
fi
exec "$SNAP_BIN" "$@"
