#!/bin/sh
# wyoming-satellite + openWakeWord, opt-in — identical logic to
# hosts/kitchen-display's own 0400-voice-satellite.hook.chroot. Voice is central to
# this device's actual purpose (voice registration, "register me as <name>"), so the
# build script's own example config defaults this to true, unlike kitchen-display's
# — but the underlying mechanism is identical and still requires real hardware
# (a mic on this specific unit) before it means anything.
set -eu

. /etc/door-panel-agent/config.env

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

VENV=/opt/voice-satellite/venv

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

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

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
