Something went wrong. Try again.
Mirroring: https://github.com/MunifTanjim/scripts.sh
Something went wrong. Try again.
scripts.sh bluetooth
2.5 kB · 142 lines
at main
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143#!/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}" indarwin*) 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}" inhelp) cat <<HELPUSAGE: bluetooth power [0|1|on|off] bluetooth restart bluetooth connectHELP exit 0 ;;esac
declare -r func="_${OS}_${cmd}"assert_func "${func}" "invalid command: ${cmd}"
$func $@