#!/bin/sh -x

scandevices() {
  # https://github.com/bluez/bluez/issues/826
  notify-send "abman" "Scanning for devices" 
  if [ "$(bluetoothctl show | grep "Powered: no")" ]; then
    bluetoothctl power on
  fi
  devices="$(bluetoothctl --timeout 5 scan on | \
    awk '/Device/ {if (NF > 3) {for (i=4; i<=NF; i++) printf $i " "; print ""} else print $3}')"
  if [ -z "$devices" ]; then
    notify-send "abman" "Error: No devices were found"
    exit 1
  fi
  
  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 "abman" "Connecting to $selection" 
  fi
}

pc_device(){
  devices="$(bluetoothctl devices | awk '{$1=$2=""; print substr($0,3)}')"
  if [ -z "$devices" ]; then
    notify-send "abman" "No previously connected devices"
    exit 0;
  fi

  selection="$(printf "%s\n" "$devices" | fuzzel -d -p "Device list: ")"
  if [ -n "$selection" ]; then
    if [ "$(bluetoothctl show | grep "Powered: no")" ]; then
      bluetoothctl power on
    fi
    mac=$(bluetoothctl devices | grep "$selection" | awk '{print $2}')
    bluetoothctl connect "$mac" & notify-send "abman" "Reconnecting to $selection"
  fi
}

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

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

switchstate() {
  if [ "$(bluetoothctl show | grep "Powered: yes")" ]; then
    bluetoothctl power off
    notify-send "abman" "Bluetooth is disabled"
  elif [ "$(bluetoothctl show | grep "Powered: no")" ]; then
    bluetoothctl power on
    notify-send "abman" "Bluetooth is enabled"
  fi
}

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