#!/bin/sh
# Headless Spotify Connect receiver (project-plan Phase 11.6).
#
# Neither spotifyd nor librespot is in Debian bookworm main, so this hook tries apt
# first (in case a backport/third-party repo has been added) and otherwise stops at a
# documented placeholder. No release URL is hardcoded on purpose: pinning a version
# here would silently 404 the moment upstream moves a tag, which is worse than an
# explicit "do this by hand" message.
set -eu

INSTALLED=""

for pkg in spotifyd librespot; do
  if apt-get install -y --no-install-recommends "$pkg" 2>/dev/null; then
    INSTALLED="$pkg"
    break
  fi
done

if [ -z "$INSTALLED" ]; then
  echo "0500-spotify-connect: neither spotifyd nor librespot is available from the"
  echo "  configured apt sources. Spotify Connect will NOT work on this image."
  echo "  To add it, pick one and re-run the build with the step filled in here:"
  echo "    a) fetch a release binary from https://github.com/Spotifyd/spotifyd/releases"
  echo "       (check the current tag yourself) into /usr/local/bin/spotifyd, or"
  echo "    b) cargo-build librespot in a build hook, or"
  echo "    c) add a third-party apt repo that carries it."
  echo "  Then drop a spotifyd.service unit in and enable it. Spotify Premium is required."
  exit 0
fi

echo "0500-spotify-connect: installed ${INSTALLED} from apt."

# Runs as the kiosk user so its MPRIS interface lands on the same session bus that
# playerctl (and therefore thinclient-agent's media_player entity) reads.
if [ "$INSTALLED" = "spotifyd" ]; then
  systemctl enable spotifyd 2>/dev/null || \
    echo "0500-spotify-connect: no packaged spotifyd unit; enable it by hand after configuring /etc/spotifyd.conf."
fi
