#!/bin/sh

# Find and toggle wireless of bluetooth devices on ThinkPads with rtl8192ce wireless
# This is derived from ibm-wireless; the rtl8192ce driver doesn't support rfkill,
# so we have to fake it. dbus code comes from the rtl8192 driver's RadioPower.sh

# Don't do anything if we're not using the r8192ce_pci driver
lsmod | grep -c r8192ce_pci || exit 0

rfkill list | sed -n -e'/tpacpi_bluetooth_sw/,/^[0-9]/p' | grep -q 'Soft blocked: yes'
bluetooth_state=$?

# Return 0 if there is, allowing you to write   if isAnyWirelessPoweredOn; then ...
isAnyWirelessPoweredOn()
{
    ENABLED=$(dbus-send --print-reply --system --type=method_call --dest=org.freedesktop.NetworkManager /org/freedesktop/NetworkManager org.freedesktop.DBus.Properties.Get string:org.freedesktop.NetworkManager string:WirelessEnabled | grep variant | awk '{ print $3 }')
    if [ "${ENABLED}" = "true" ]; then
	return 0;
    elif [ "${ENABLED}" = "false" ]; then
	return 1;
    else 
        # Something's broken, might as well assume wireless is on
        return 0;
    fi
}

# Enable/disable via NetworkManager
# Takes 1 parameter, either 'true' or 'false' for on/off
setWirelessState()
{
    dbus-send --system --type=method_call --dest=org.freedesktop.NetworkManager /org/freedesktop/NetworkManager org.freedesktop.DBus.Properties.Set string:org.freedesktop.NetworkManager string:WirelessEnabled variant:boolean:$1
}

# Note that this always alters the state of the wireless!
if ! isAnyWirelessPoweredOn; then
    setWirelessState "true"
else
    setWirelessState "false"
fi

# Sequence is Both on, Both off, Wireless only, Bluetooth only
if ! isAnyWirelessPoweredOn; then
    # Wireless was turned off
    if [ "$bluetooth_state" = 0 ]; then
        rfkill unblock bluetooth
    else
        rfkill block bluetooth
    fi
fi
