# Paul Sladen, 2006-03-28, 2007-03-26
# Luca Niccoli <lultimouomo@gmail.com>, 2010-06-23
# Library functions to check/change status of wireless

WLAN_RFKILLS=`for RFKILL in /sys/class/rfkill/rfkill*; do if [ $(cat $RFKILL/type) = wlan ]; then echo $RFKILL/state; fi; done`

haveDevRfkill()
{
  [ -c /dev/rfkill ] && [ -x /usr/sbin/rfkill ]
}

# Return 0 if there is, allowing you to write   if isAnyWirelessPoweredOn; then ...
isAnyWirelessPoweredOn()
{
    if haveDevRfkill; then
        rfkill list wlan | grep -q "Soft blocked: no"
        return $?
    else
        for RFKILL in $WLAN_RFKILLS ; do
            if [ -r "$RFKILL" ] && [ "$(cat "$RFKILL")" -eq 1 ]; then
                return 0
            fi
        done
    fi
    # otherwise return failure  
    return 1
}

# Takes no parameters, toggles all wireless devices.
toggleAllWirelessStates()
{
    # If rfkill is handled by the kernel, don't touch it
    if ! grep -q '^H.*\brfkill\b' /proc/bus/input/devices; then
        if isAnyWirelessPoweredOn; then
            # ifconfig down wireless interfaces, helps with some buggy driver            
            for WIFACE in `iwconfig 2>/dev/null |grep -o '^[[:alnum:]]*'`; do
                ifconfig $WIFACE down || :
            done
            if haveDevRfkill; then
                rfkill block wlan
            else
                for RFKILL in $WLAN_RFKILLS; do
                    [ -w $RFKILL ] && echo 0 > $RFKILL
                done
            fi
        else
            if haveDevRfkill; then
                rfkill unblock wlan
            else
                for RFKILL in $WLAN_RFKILLS; do
                    [ -w $RFKILL ] && echo 1 > $RFKILL
                done
            fi
        fi
    fi
    # Is wireless on now? Set the interfaces up and poke wicd
    sleep 5
    if isAnyWirelessPoweredOn; then
        for WIFACE in `iwconfig 2>/dev/null |grep -o '^[[:alnum:]]*'`; do
            ifconfig $WIFACE up || :
        done
        [ -x /usr/share/wicd/daemon/autoconnect.py ] &&  /usr/share/wicd/daemon/autoconnect.py 
    fi
}

# Pass '1' to blink suspending LED and '0' to stop LED
setLEDThinkpadSuspending()
{
    action=`test "$1" -ne 0 && echo blink || echo off`
    test -w /proc/acpi/ibm/led && echo -n 7 "$action" > /proc/acpi/ibm/led
}
