#!/bin/sh
# wyoming-satellite + openWakeWord, for the mic-enabled rooms only.
set -eu

. /etc/thinclient-agent/config.env

if [ "${ENABLE_VOICE_SATELLITE}" != "true" ]; then
  echo "0600-voice-satellite: ENABLE_VOICE_SATELLITE is false, skipping (this is the"
  echo "  default — only images destined for the specific rooms that have a microphone"
  echo "  should enable it)."
  exit 0
fi

VENV=/opt/voice-satellite/venv

# A venv rather than `pip3 install --break-system-packages`: bookworm's system
# interpreter is externally managed (PEP 668), and these packages pull a large,
# fast-moving dependency tree (onnxruntime, numpy) that would otherwise be free to
# overwrite apt-managed versions the rest of the image depends on.
python3 -m venv "$VENV"
"$VENV/bin/pip" install --upgrade pip wheel setuptools

# VERIFY BEFORE THE FIRST REAL BUILD: upstream's documented install path is a git
# clone + script/setup rather than PyPI. If either of these names is not on PyPI,
# swap this for:
#   git clone https://github.com/rhasspy/wyoming-satellite /opt/voice-satellite/src
#   /opt/voice-satellite/src/script/setup
if ! "$VENV/bin/pip" install wyoming-satellite wyoming-openwakeword; then
  echo "0600-voice-satellite: WARNING — pip install failed. Fall back to the upstream"
  echo "  git-clone install described in the comment above this line."
  exit 0
fi

cat > /etc/systemd/system/wyoming-openwakeword.service <<EOF
[Unit]
Description=Wyoming openWakeWord
After=network.target

[Service]
Type=simple
ExecStart=${VENV}/bin/wyoming-openwakeword --uri tcp://127.0.0.1:10400 --preload-model ${VOICE_WAKE_WORD}
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

# --mic-command/--snd-command use the ALSA default device because no thin-client
# hardware has been chosen yet (project-plan open decision #7). Once the mic is known,
# replace `default` with the real `arecord -L` device name.
cat > /etc/systemd/system/wyoming-satellite.service <<EOF
[Unit]
Description=Wyoming satellite (${VOICE_SATELLITE_NAME})
Wants=wyoming-openwakeword.service
After=network.target wyoming-openwakeword.service

[Service]
Type=simple
User=${KIOSK_USERNAME}
ExecStart=${VENV}/bin/wyoming-satellite \\
  --name '${VOICE_SATELLITE_NAME}' \\
  --uri tcp://0.0.0.0:10700 \\
  --mic-command 'arecord -D default -r 16000 -c 1 -f S16_LE -t raw' \\
  --snd-command 'aplay -D default -r 22050 -c 1 -f S16_LE -t raw' \\
  --wake-uri tcp://127.0.0.1:10400 \\
  --wake-word-name '${VOICE_WAKE_WORD}'
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

systemctl enable wyoming-openwakeword
systemctl enable wyoming-satellite
