#!/bin/bash
#
# Blueconnect.sh 
# Work in progress version
# ---------------------------------------------------------
# This script is intended to help the users to estabilish
# a dialup connection whit a cell phone, over the Bluetooth
# Protocol. It require zenity as mandatory dependence.
# See README for furter info.
# 
# The script is developed from the Linux4One team, and is 
# relased under the LGPL2 terms.
#
# Official support forum www.linux4one.it
#
# --------------------------------------------------------
# Used Variables:
#
# LOOP, FLAG & FOUND temporary storage variables
# BTA   --> Used bluetooth device address 
# CHAN  --> DUN service channel (usually 1)
# BTAPP --> Used for store bluetooth-applet is loaded or not 

#   --------- Start -----------

# Need to check if bluetooth subsitem is active
# if not warn the user and exit

if [ "`/bin/pidof hcid`" = "" ]; then 
    zenity --error --text "Bluetooth subsystem not correctly started"
    exit 1
fi

#Check that the bluetooth-applet is loaded (useful as pin helper)
#If not load it and kill it at the end (BTAPP=0)
#If yes don't kill it at the end (BTAPP=1)
BTAPP=1
if [ "`/bin/pidof bluetooth-applet`" = "" ]; then 
    /usr/bin/bluetooth-applet &
    BTAPP=0
fi

# Scan for reachable device and store theyr address
zenity --info --text="Activate device Bluetooth\n\nand press enter"
hcitool -i hci0 scan > /tmp/scans
echo "zenity --list " > menu
echo "--title=\"Choose the Bluetooth device\"" >> menu
echo "--column=\"Radio\" --column=\"Name\" --column=\"Address\" --radiolist --print-column=3 " >> menu
cat /tmp/scans | awk '{ FS = "	"  } ; {if ($1 != "Scanning") print "FALSE \"" $3 "\" \"" $2 "\" "}' >> menu
MENU=$(cat menu)
echo $MENU > menu

# Let the user choose the device and check it supports DUN
LOOP=0
while [ $LOOP = 0 ]; do
        BTA=$(sh menu)
	echo $BTA
	if [ "$BTA" = "" ]; then
		LOOP=1
	else
		FLAG=$(sdptool search --bdaddr "$BTA" DUN | grep Channel)
		if [ "$FLAG" = "" ]; then
        		zenity --error --text="Selected device doesn't offer DUN service\n\nChose another one"
		else
			LOOP=1
			FOUND=1        	
		fi              
	fi
done
rm /tmp/scans

# Set Up the connection 
if [ "$FOUND" = "1" ]; then
   
   # Bind the DUN device channel with /dev/rfcomm0
   CHAN=${FLAG:(-2)}
   echo $CHAN
   /usr/bin/rfcomm connect 0 "$BTA" $CHAN & 
   
   # Give some information to the user and launch gnome-ppp
   
   zenity --info --text "Now we will launch gnome-ppp for the ppp connection\nRemember to setup modem port to /dev/rfcomm0 \nTo set the correct APN in the modem init string\nand to set the right Phonenumber ( usually *99# )"
   gnome-ppp
      
  
fi   

# stop all the services started

killall rfcomm
if [ "$BTAPP" = "0" ]; then   
   killall bluetooth-applet
   killall obex-data-server
fi