#!/bin/sh
# wyoming-satellite + openWakeWord, opt-in (docs/project-plan.md Phase 6/17) — this is
# what makes voice registration ("register me as <name>") possible on this device.
# Identical logic to hosts/thin-client's 0600-voice-satellite.hook.chroot.
set -eu

. /etc/kitchen-display-agent/config.env

if [ "${ENABLE_VOICE_SATELLITE}" != "true" ]; then
  echo "0400-voice-satellite: ENABLE_VOICE_SATELLITE is false, skipping (this is the"
  echo "  default — voice registration needs a real microphone; don't enable this"
  echo "  until one is attached)."
  exit 0
fi

VENV=/opt/voice-satellite/venv

python3 -m venv "$VENV"
"$VENV/bin/pip" install --upgrade pip wheel setuptools

# VERIFY BEFORE THE FIRST REAL BUILD — same caveat as the thin client's identical
# hook: upstream's documented install path is a git clone + script/setup rather than
# PyPI. If either name isn't on PyPI, fall back to that instead.
if ! "$VENV/bin/pip" install wyoming-satellite wyoming-openwakeword; then
  echo "0400-voice-satellite: WARNING — pip install failed. Fall back to the upstream"
  echo "  git-clone install: https://github.com/rhasspy/wyoming-satellite"
  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 — no kitchen-display
# hardware has been chosen yet, same open item as every other host in this project.
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
