#!/usr/bin/env bash

emit() {
  local powered=false connected=false device=""

  if bluetoothctl show 2>/dev/null | grep -q "Powered: yes"; then
    powered=true
    while IFS= read -r line; do
      local mac info
      mac=$(echo "$line" | awk '{ print $2 }')
      info=$(bluetoothctl info "$mac" 2>/dev/null)
      if echo "$info" | grep -q "Connected: yes"; then
        device=$(echo "$info" | awk -F': ' '/^\tName:/ { print $2; exit }')
        connected=true
        break
      fi
    done < <(bluetoothctl devices 2>/dev/null)
  fi

  printf '{"powered":%s,"connected":%s,"device":"%s"}\n' "$powered" "$connected" "$device"
}

emit

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

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

# bluetoothctl monitor for reactive device connect/disconnect events
(bluetoothctl monitor 2>/dev/null | grep --line-buffered -E "Powered|Connected|Device") > "$pipe" &

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