#!/bin/sh
# Installs a Spotify Connect backend + enables the shared spotify-connect.service
# unit into the audio-endpoint image (amd64). The only hook this image needs,
# hence 0100 — mirrors the numbering convention (and, below, the exact
# apt-first/documented-fallback logic and package order) of
# hosts/thin-client/live-build/config/hooks/normal/0500-spotify-connect.hook.chroot.
# Not a divergent reimplementation of that hook's reasoning, the same one reused.
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 "0100-spotify-connect: neither spotifyd nor librespot is available from the"
  echo "  configured apt sources. Spotify Connect will NOT work on this image."
  echo "  See hosts/audio-endpoint/README.md's Spotify Connect install section for"
  echo "  the manual fallback routes (a release binary, a cargo build, raspotify,"
  echo "  or a third-party apt repo) — same options documented for the arm64 image."
  exit 0
fi

echo "0100-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 "0100-spotify-connect: could not enable spotify-connect.service — check it landed at /etc/systemd/system/ via includes.chroot."
