#!/usr/bin/env bash
# install-service.sh — install the audio hub + phone-mic server as always-on launchd agents.
#   ./install-service.sh            install (or reinstall) and start both
#   ./install-service.sh uninstall  stop and remove both
set -euo pipefail
DIR="$(cd "$(dirname "$0")" && pwd)"
LA="$HOME/Library/LaunchAgents"
UID_N="$(id -u)"
mkdir -p "$LA" "$DIR/.run"

# stop any manual (billo-audio.sh) copies so the ports are free
"$DIR/billo-audio.sh" stop >/dev/null 2>&1 || true

for name in billo-audio-hub phone-mic; do
  src="$DIR/$name.plist"
  label="$(/usr/libexec/PlistBuddy -c 'Print :Label' "$src")"
  dst="$LA/$label.plist"
  launchctl bootout "gui/$UID_N/$label" 2>/dev/null || true
  if [ "${1:-}" = "uninstall" ]; then
    rm -f "$dst"; echo "removed: $label"; continue
  fi
  plutil -lint "$src" >/dev/null
  cp "$src" "$dst"
  launchctl bootstrap "gui/$UID_N" "$dst"
  echo "installed + started: $label"
done
[ "${1:-}" = "uninstall" ] && exit 0
sleep 3
"$DIR/billo-audio.sh" status
echo "logs: $DIR/.run/service-*.log"
