#!/bin/sh
# Installs a Spotify Connect backend into the audio-endpoint image (arm64).
# Intended to run chrooted into the target rootfs during the rpi-image-gen
# build — see config/audio-endpoint.yaml's script-hook reference. The exact
# rpi-image-gen integration-point key for "run this chrooted at build time" is
# one of the things flagged unverified in hosts/audio-endpoint/README.md;
# adjust *that wiring* if the tool's actual hook mechanism differs, not this
# script's own logic.
#
# Mirrors hosts/thin-client/live-build/config/hooks/normal/
# 0500-spotify-connect.hook.chroot's exact reasoning and package order: neither
# spotifyd nor librespot is in Debian bookworm main, so try apt first (in case
# a backport/third-party repo has been added) and otherwise stop at a
# documented placeholder — never hardcode a release URL that would silently
# 404 later.
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 "install-spotify-connect: neither spotifyd nor librespot is available from"
  echo "  the 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"
  echo "       https://github.com/librespot-org/librespot/releases (check the"
  echo "       current tag yourself) into /usr/bin/librespot, or"
  echo "    b) cargo-build librespot in this hook, or"
  echo "    c) use raspotify instead (https://github.com/dtcooper/raspotify) — it"
  echo "       wraps librespot with its own packaging and systemd unit; if you use"
  echo "       it, drop this repo's spotify-connect.service/spotify-connect-start"
  echo "       in favour of its own unit rather than layering both, or"
  echo "    d) add a third-party apt repo that carries one of the above."
  echo "  Spotify Premium is required either way."
  exit 0
fi

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

# Dedicated unprivileged system account — see spotify-connect.service's own
# User=/Group= lines. --no-create-home: this account never needs a home
# directory, just membership in 'audio' for ALSA device access.
if ! id spotify-connect >/dev/null 2>&1; then
  useradd --system --no-create-home --gid audio spotify-connect
fi

systemctl enable spotify-connect.service 2>/dev/null || \
  echo "install-spotify-connect: could not enable spotify-connect.service — check it landed at /etc/systemd/system/ (see config/audio-endpoint.yaml's file list)."
