#!/usr/bin/env bash
#
# Install the mic-follow agent for ONE client, on the machine that client is.
#
#     mic-follow/setup-client.sh <node_id>
#
# Run it on that person's desktop, from a checkout of this repo. It generates from
# CoreSystemConfig.json, installs the client config (mode 0600 — it holds the MQTT
# password) and a systemd --user unit, and starts it.
#
# A second person's desktop runs the same command with their own node_id. Nothing here
# is specific to one machine except the argument.
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
DIR="${REPO_ROOT}/mic-follow"
# shellcheck source=/dev/null
source "${REPO_ROOT}/tools/lib/coreconfig.sh"

NODE_ID="${1:-}"
[[ -n "$NODE_ID" ]] || core_die "usage: setup-client.sh <node_id>  (from mic_follow.clients in CoreSystemConfig.json)"

core_load
[[ "$CORE_MIC_FOLLOW_ENABLED" == "true" ]] || core_die \
  "mic_follow.enabled is false in $(basename "$CORE_CONFIG_PATH")"

core_log "Generating"
"${DIR}/generate.py" "$CORE_CONFIG_PATH"
GEN="${DIR}/generated/${NODE_ID}"
[[ -d "$GEN" ]] || core_die "no client '${NODE_ID}' in the config — have: $(ls -1 "${DIR}/generated" | grep -v '^ha-package$' | tr '\n' ' ')"

core_log "Checking this machine can see its microphones"
if ! command -v pactl >/dev/null; then
  core_warn "pactl is not installed — the agent cannot switch anything without it"
  core_warn "  Debian/Ubuntu: apt install pulseaudio-utils      Arch: pacman -S libpulse"
else
  "${DIR}/desktop_agent.py" --list-sources || core_warn "could not list audio sources"
fi

core_log "Installing"
mkdir -p "$HOME/.config/mic-follow" "$HOME/.config/systemd/user"
install -m 600 "${GEN}/client.json" "$HOME/.config/mic-follow/client.json"
# Any remote microphones this client can switch to. Each one names a machine and an
# SSH user; remote-mic.sh reads them by room name.
shopt -s nullglob
for env_file in "${GEN}"/remote-*.env; do
  install -m 600 "$env_file" "$HOME/.config/mic-follow/$(basename "$env_file")"
  echo "  remote microphone: $(basename "$env_file" .env | sed 's/^remote-//')"
done
shopt -u nullglob
install -m 644 "${GEN}/mic-follow-${NODE_ID}.service" \
  "$HOME/.config/systemd/user/mic-follow.service"

if ! systemctl --user daemon-reload 2>/dev/null; then
  core_warn "systemctl --user is not available here — the unit is installed but not loaded"
elif systemctl --user enable --now mic-follow.service; then
  echo "  started — follow it with: journalctl --user -fu mic-follow"
else
  core_warn "could not start it — try: systemctl --user status mic-follow"
fi

cat <<EOF

Left to do, and none of it is on this machine:

  [ ] Home Assistant: install the generated package
        ${DIR}/generated/ha-package/mic_follow.yaml
      next to stream-dock's, in <HA config>/packages/, then reload YAML.

  [ ] identity: paste the line from
        ${DIR}/generated/identity-toggles.env
      into /opt/smart-home/identity/identity.env and restart identity.
      Without it the Pebble app sees no toggles at all.

  [ ] Stream Dock: bind the toggle key as described in
        ${DIR}/generated/dock-bindings.md

  [ ] For each remote microphone, check the SSH path this desktop will use:
        ssh <user>@<host> pw-record --help
      That one command is the whole transport. If it works, the microphone works;
      if it does not, no amount of Home Assistant configuration will help.

  [ ] Check the presence entity actually reports area_ids:
        Developer Tools -> States -> the presence_entity for this client.
      If its state is a friendly room name rather than an area_id, the automation
      will never match and the microphone will never move — see README.md section 3.

EOF
