#!/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
      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
bluetoothctl monitor 2>/dev/null | while IFS= read -r line; do
  case "$line" in
    *"Powered"*|*"Connected"*|*"Device"*) emit ;;
  esac
done
