# shellcheck shell=dash

___x_cmd_mac_bluetooth(){
    [ "$#" -gt 0 ] || set -- status

    local op="$1";  shift
    case "$op" in
        enable|disable|status|info)
            ___x_cmd_mac_bluetooth_"$op" "$@"                 ;;
        -h|--help)
            ___x_cmd help -m mac bluetooth                    ;;
        *)  N=mac M="Unknown subcmd -> $op" log:ret:64        ;;
    esac
}

___x_cmd_mac_bluetooth_enable(){
    ___x_cmd_mac_bluetooth___ctrl 1
}

___x_cmd_mac_bluetooth_disable(){
    ___x_cmd_mac_bluetooth___ctrl 0
}

___x_cmd_mac_bluetooth___ctrl(){
    ___x_cmd sudo bash -c "
        defaults write /Library/Preferences/com.apple.Bluetooth ControllerPowerState -int $1 && killall -HUP bluetoothd
    "
}

# TODO: The domain/default pair of (/Library/Preferences/com.apple.Bluetooth, ControllerPowerState) does not exist
___x_cmd_mac_bluetooth_status(){
    if [ "$(___x_cmd_mac___cmd defaults read /Library/Preferences/com.apple.Bluetooth ControllerPowerState)" = 1 ]; then
        printf "Bluetooth: %s\n" ON
    else
        printf "Bluetooth: %s\n" OFF
    fi
}

___x_cmd_mac_bluetooth_info(){
    ___x_cmd_mac___cmd system_profiler SPBluetoothDataType | ___x_cmd yml fmt
}

