#!/bin/bash

# btctl - Script to connect or disconnect Bluetooth devices by partial name

function erro() {
    echo "$1" 1>&2
}

# Function to get device address by partial name
function get_device_addr() {
    local partial_name=$1
    local devices_found
    local device_count

    if [ -z "$partial_name" ]; then
        echo "Device name not provided." >&2
        return 1
    fi

    # Search for devices containing the partial name, ignoring case
    devices_found=$(bluetoothctl devices | grep -i "$partial_name")

    # Count how many devices were found
    device_count=$(wc -l <<<"$devices_found")

    if [ "$device_count" -eq 0 ]; then
        erro "Device containing '$partial_name' not found." >&2
        return 1
    elif [ "$device_count" -gt 1 ]; then
        erro "Multiple devices containing '$partial_name' found. Please specify further."
        erro "$devices_found"
        return 1
    fi

    # Extract and echo the device address of the single matching device
    awk '{print $2}' <<<"$devices_found"
}

function usage() {
    echo "Usage: $(basename "$0") {connect|disconnect|list} <partial_device_name>"
}

function perform_action() {
    local action=$1
    local partial_name=$2
    local device_addr

    # Check if getting device address was successful
    if ! device_addr=$(get_device_addr "$partial_name"); then
        return 1
    fi

    if ! bluetoothctl "$action" "$device_addr"; then
        echo "$action to device with address $device_addr failed." >&2
        return 1
    fi
}

case "$1" in
list)
    bluetoothctl devices
    ;;
connect | disconnect)
    perform_action "$1" "$2"
    ;;
*)
    usage
    exit 1
    ;;
esac
