#!/usr/bin/env bash
# Bluetooth status / toggle via bluetoothctl.

powered() { bluetoothctl show 2>/dev/null | awk '/Powered:/{print $2; exit}'; }

case "${1:-status}" in
  toggle)
    if [ "$(powered)" = yes ]; then bluetoothctl power off
    else bluetoothctl power on; fi
    ;;
  status|*)
    if [ "$(powered)" != yes ]; then
      jq -nc '{icon:"󰂲",label:"Off",on:false}'
      exit 0
    fi
    dev=$(bluetoothctl devices Connected 2>/dev/null | head -1 | cut -d' ' -f3-)
    if [ -n "$dev" ]; then
      jq -nc --arg d "$dev" '{icon:"󰂱",label:$d,on:true}'
    else
      jq -nc '{icon:"󰂯",label:"On",on:true}'
    fi
    ;;
esac
