#!/bin/sh
# Starts whichever Spotify Connect backend actually got installed on this image —
# librespot or spotifyd. Installed to /usr/local/bin/spotify-connect-start,
# invoked by spotify-connect.service. Exactly one of these binaries exists on any
# given image (see the apt-first/documented-fallback install logic in both build
# pipelines' hooks, mirroring hosts/thin-client's own
# 0500-spotify-connect.hook.chroot); this wrapper is what lets the systemd unit
# stay one static file regardless of which one it turned out to be.
#
# DEVICE NAME: always $(hostname), read fresh at every start, never baked in.
# Per-room identity is set differently on each variant — Raspberry Pi Imager's OS
# Customisation (arm64, per-flash) or IMAGE_HOSTNAME at build time (amd64,
# per-build) — see hosts/audio-endpoint/README.md's "Per-room identity" sections.
# Reading the hostname here rather than a baked-in name is what lets one shared
# unit/wrapper work correctly either way.
#
# ALSA DEVICE: ${ALSA_DEVICE:-default}. The arm64 image sets this to a fixed
# `hw:0` via a systemd drop-in (safe once onboard audio is disabled and the
# HiFiBerry is the only card left — see the hifiberry-amp2 config.txt fragment).
# The amd64 image ships with no override at all — a generic mini PC's USB DAC
# enumeration index isn't something this repo can know in advance (it may also
# have onboard audio competing for card 0, and which one wins varies by board),
# so guessing one would be exactly the kind of "build against a guess" this
# project avoids elsewhere (gesture-config.json's camera_device, the ESP32
# firmware's weather_entity_id). See hosts/audio-endpoint/README.md's amd64
# section for the one-time `aplay -l` + systemd drop-in step this leaves for
# whoever sets up that specific box.
set -eu

NAME="$(hostname)"
DEVICE="${ALSA_DEVICE:-default}"

if command -v librespot >/dev/null 2>&1; then
  exec librespot --name "$NAME" --backend alsa --device "$DEVICE" \
    --bitrate 320 --initial-volume 100 --device-type speaker
fi

if command -v spotifyd >/dev/null 2>&1; then
  exec spotifyd --no-daemon --device-name "$NAME" --backend alsa \
    --device "$DEVICE" --bitrate 320 --initial-volume 100
fi

echo "spotify-connect-start: neither librespot nor spotifyd is installed on this" >&2
echo "  image — see hosts/audio-endpoint/README.md's Spotify Connect install section." >&2
exit 1
