#!/bin/sh -x
# Created by λmolinae

checkstate() {
  if [ "$(bluetoothctl show | grep "Powered: yes")" ]; then
    echo "󰂯 Bluetooth ON"
  else
    echo "󰂲 Bluetooth OFF"
  fi
}

switchstate() {
  case "$(checkstate | fuzzel -d)" in
    "󰂯 ON")
      bluetoothctl power off
      notify-send "Bluetooth" "Bluetooth is disabled"
      ;;
    "󰂲 OFF")
      bluetoothctl power on
      notify-send "Bluetooth" "Bluetooth is enabled"
      ;;
    *) exit ;;
  esac
}

scandevices() {
  # https://github.com/bluez/bluez/issues/826
  notify-send "Bluetooth" "Scanning for devices"
  bluetoothctl --timeout 5 scan on
  devices=$(bluetoothctl devices | awk '{$1=$2=""; print substr($0,3)}')
  if [ -z "$devices" ]; then
    notify-send "Bluetooth" "Error: No devices were found"
    exit 1
  fi
  
  # TODO: Remove previously connected devices.
  selection="$(printf "%s\n" "$devices" | fuzzel -d -p "Available devices: ")"
  if [ -n "$selection" ]; then
    mac=$(bluetoothctl devices | grep "$selection" | awk '{print $2}')
    bluetoothctl connect "$mac"
    notify-send "Bluetooth" "Connecting to $selection"
  fi
}

toggledisc() {
  if [ "$(bluetoothctl show | grep "Discoverable: yes")" ]; then
    bluetoothctl discoverable off
    notify-send "Bluetooth" "Discoverable off"
  else
    bluetoothctl discoverable on
    notify-send "Bluetooth" "Set device as discoverable for 3 minutes"
  fi
}

togglepair() {
  if [ "$(bluetoothctl show | grep "Pairable: yes")" ]; then
    bluetoothctl pairable off
    notify-send "Bluetooth" "Pairable off"
  else
    bluetoothctl pairable on
    notify-send "Bluetooth" "Device is now pairable"
  fi
}

case $(printf "%s\n" "󰂯 Connect Device" "󰂱 Toggle discoverable" "󰂰 Toggle Pairable" "󰂳 Change State" | fuzzel -d) in
  "󰂯 Connect Device") scandevices ;;
  "󰂱 Toggle discoverable") toggledisc ;;
  "󰂰 Toggle Pairable") togglepair ;;
  "󰂳 Change State") switchstate ;;
  *) exit ;;
esac
