#!/bin/sh
#
# Available at http://ferrari.databa.se/3400/f8/dun-bind.sh
#
# A verbose sample script for finding the Dial Up Networking
# channel on a Bluetooth device and binding a /dev/rfcomm port to it.
#
# By Sven-Göran Bergh, 2005-11-03
# Update 2007-04-03 Added release of passive/closed rfcomm port.
#

# Use this /dev/rfcomm port
RFPORT=1

# Name of Bluetooth device to bind to:
BTNAME="S-Gs P900"

success() {
  echo -e $"\\033[60G[  \\033[1;32mOK\\033[0;39m  ]"
  return 0
}

failure() {
  echo -e $"\\033[60G[\\033[1;31mFAILED\\033[0;39m]"
  exit 1
}

# Check that local Bluetooth device is active
echo -n $"Checking for local Bluetooth device..."
hciconfig | grep 'UP RUNNING' &> /dev/null \
    &&  success || failure

# If the rfcomm port exists but is currently not in use, try to release it
if [ "`rfcomm show ${RFPORT} 2> /dev/null | awk -- '{print $5}'`" == "closed" ];
then
    echo -n $"Trying to free closed port /dev/rfcomm${RFPORT}..."
    rfcomm release ${RFPORT} &> /dev/null \
	&&  success || failure
fi

# Check if the rfcomm port is free
echo -n $"Checking that /dev/rfcomm${RFPORT} is free..."
rfcomm show ${RFPORT} &> /dev/null \
    && failure || success

# Check for the remote Bluetooth device
echo -n $"Searching for remote Bluetooth device ${BTNAME}..."
BTADDR=`hcitool scan | grep "${BTNAME}" | awk -- '{print $1}'`
[ "${BTADDR}" ] && success || failure

# Find the Dial Up Networking channel
echo -n $"Searching for Dial Up Networking service..."
DUN=`sdptool search --bdaddr ${BTADDR} DUN \
    | awk -- '/Channel/ {print $2}'`
[ "${DUN}" ] && success || failure

# Bind the rfcomm port to the DUN channel
echo -n $"Binding /dev/rfcomm${RFPORT} to DUN channel ${DUN}..."
rfcomm bind ${RFPORT} ${BTADDR} ${DUN} \
    && success || failure
