#!/bin/bash


function btstatus(){
  device_mac_list=$(bluetoothctl devices Paired | awk '{print $2}')
  device_json_array=()

  for m in ${device_mac_list};do
    device_name="$(bluetoothctl info ${m} | grep 'Name: ' | sed 's/.*Name: //')"
    device_connected="$(bluetoothctl info ${m} | grep 'Connected: ' | sed 's/.*Connected: //')"
    device_icon="$(bluetoothctl info ${m} | grep 'Icon: ' | sed 's/.*Icon: //')"
    case "${device_icon}" in
      "input-mouse")
        device_icon="🖯"
        ;;
      "phone")
        device_icon=""
        ;;
      "input-keyboard")
        device_icon=""
        ;;
      "input-gaming")
        device_icon=""
        ;;
      "audio-headphones")
        device_icon=""
        ;;
      "audio-headset")
        device_icon=""
        ;;
      "computer")
        device_icon=""
        ;;
    esac
    device_json=$( jq -n --arg name "${device_name}" --arg connected "${device_connected}" --arg icon "${device_icon}" --arg address "${m}" '{name: $name, connected: $connected, icon: $icon, address: $address}')
    device_json_array+=("${device_json}")
  done
  devices_json=$(printf '%s\n' "${device_json_array[@]}" | jq -s .)
  echo ${devices_json}
}

btstatus

dbus-monitor --profile "interface='org.blueman.Applet',member='MenuChanged'" | while read -r event; do
  btstatus
done
