#!/usr/bin/env bash

emit() {
  local first=true arr=""
  while IFS= read -r line; do
    local mac name connected
    mac=$(echo "$line" | awk '{ print $2 }')
    name=$(echo "$line" | awk '{ $1=$2=""; sub(/^ +/, ""); print }')
    info=$(bluetoothctl info "$mac" 2>/dev/null)
    connected=$(echo "$info" | grep -q "Connected: yes" && echo true || echo false)
    $first || arr="${arr},"
    arr="${arr}{\"mac\":\"${mac}\",\"name\":\"${name}\",\"connected\":${connected}}"
    first=false
  done < <(bluetoothctl devices 2>/dev/null)
  echo "[${arr}]"
}

emit

tmp=$(mktemp -d)
pipe="$tmp/bt-dev-events"
mkfifo "$pipe"
trap 'rm -rf "$tmp"; kill 0 2>/dev/null' EXIT INT TERM

# Poll every 3s as fallback for missed events
(while true; do sleep 3; echo poll; done) > "$pipe" &

# Reactive updates from D-Bus
(bluetoothctl monitor 2>/dev/null | grep --line-buffered -E "Connected|Device|Powered") > "$pipe" &

while IFS= read -r _ < "$pipe"; do
  emit
done
