Nick's Location Changer - 1.0

% cat bin/locationchanger

#!/bin/bash
# Nick's Location Changer - 1.0
# 
# Automatically enables or disables Bluetooth depending on presence of
# the Thunderbolt adapter (en3).
#
# That makes it great for plugging and unplugging laptops, since
# Bluetooth keyboards and trackpads are really only used when attached
# to the Thunderbolt monitor.
#
# This makes sharing one Thunderbolt monitor between two systems (say,
# a Macbook and a Mini) really easy.  The inspiration came from the
# original LocationChanger:
#   http://tech.inhelsinki.nl/locationchanger/
#
# You should use the instructions to have OS X call the script. I also
# couldn't have done it without blueutil:
#
#     http://www.frederikseiffert.de/blueutil
#
# Good luck!
#
# WARNINGS
#
# XXX NMK - NO error checking. I'm sure this can break in many ways.

# XXX NMK - Detect interface automatically. For now use en3.  This is
#           the Thunderbolt interface on my MacBook Pro and MacBook Air.
INTERFACE=en3

# LOG
#
# To tail log: sudo tail -f /var/log/system.log | grep 'Bluetooth:' 
# To view log: sudo cat /var/log/system.log | grep 'Bluetooth:' 
#
LOGGER=/usr/bin/logger

BLUEUTIL=/usr/local/bin/blueutil
# http://www.frederikseiffert.de/blueutil/" 

# BLUE TOOTH STATUS
# We don't check for "off", we just check for "on".
BLUESTATUSSTR="0==on, 1==!on"
BLUESTATUS=`${BLUEUTIL} status | /usr/bin/awk '{print $2}'`
if [ ${BLUESTATUS} == "on" ]; then
    BLUESTATUS=0
else
    BLUESTATUS=1
fi
BLUESTATUSSTR="Bluetooth: now ${BLUESTATUS}; ${BLUESTATUSSTR})."

${LOGGER} "Location Changed - begin. ${BLUESTATUSSTR}".

# If the interface exists, "enable" bluetooth. Otherwise "disable."
/sbin/ifconfig ${INTERFACE}
if [ $? -eq 0 ]; then
    ${LOGGER} "${INTERFACE} exists, enabling ${BLUESTATUSSTR}."
    if [ ${BLUESTATUS} -ne 0 ]; then
        ${BLUEUTIL} on
    fi
else
    ${LOGGER} "${INTERFACE} does not exist, disabling ${BLUESTATUSSTR}."
    if [ ${BLUESTATUS} -eq 0 ]; then
        ${BLUEUTIL} off
    fi
fi

${LOGGER} "Location Changed - end. ${BLUESTATUSSTR}".

# XXX NMK - We exit with the same status as blueutil.
exit ${BLUESTATUS}