#!/usr/bin/env bash set -euo pipefail assert_command() { if ! type "${1}" >/dev/null 2>&1; then echo "${2:-"command not found: ${1}"}" exit 1 fi } assert_val() { if [[ -z "${1}" ]]; then echo "${2}" exit 1 fi } assert_func() { if ! declare -F "${1}" >/dev/null; then echo "${2}" exit 1 fi } _darwin_power() { case "${1:-"?"}" in 1 | on) blueutil --power 1 ;; 0 | off) blueutil --power 0 ;; ?) blueutil --power ;; *) exit 1 ;; esac } _darwin_restart() { bluetooth power off bluetooth power on } _darwin_connect() { local disconnect="no" while (("$#")); do case "${1}" in --disconnect) disconnect="yes" shift ;; *) shift ;; esac done local -r blob="$(blueutil --format=json --paired)" local -r name="$(echo "${blob}" | jq -r '.[].name' | fzf)" local -r id="$(echo "${blob}" | jq -r ".[] | select(.name==\"${name}\") | .address")" if [[ "${disconnect}" = "yes" ]]; then blueutil --disconnect "${id}" fi blueutil --connect "${id}" } _linux_power() { case "${1:-"?"}" in 1 | on) bluetoothctl power on ;; 0 | off) bluetoothctl power off ;; ?) bluetoothctl show | grep --quiet "Powered: yes" && echo "1" || echo "0" ;; *) exit 1 ;; esac } _linux_restart() { if [[ -z "$(bluetoothctl list)" ]]; then sudo modprobe -r btusb sudo modprobe btusb while [[ -z "$(bluetoothctl list)" ]]; do sleep 0.2 done fi bluetooth power off bluetooth power on } _linux_connect() { local disconnect="no" while (("$#")); do case "${1}" in --disconnect) disconnect="yes" shift ;; *) shift ;; esac done local -r blob="$(bluetoothctl paired-devices)" local -r name="$(echo "${blob}" | sed -e 's/\S* \S* //' | fzf)" assert_val "${name}" "failed to select device" local -r id="$(echo "${blob}" | grep "${name}" | awk '{ print $2 }')" if [[ "${disconnect}" = "yes" ]]; then bluetoothctl disconnect "${id}" fi bluetoothctl connect "${id}" } declare OS="" case "${OSTYPE}" in darwin*) assert_command blueutil OS="darwin" ;; linux*) assert_command bluetoothctl OS="linux" ;; *) echo "Unsupported OS!" exit 1 ;; esac declare -r cmd="${1:-"help"}" shift || true case "${cmd}" in help) cat <