#!/usr/bin/perl -w

# John Cooper 05/04/03
# Released under the GNU GPL license
# tested under 2.4.20-mh6 + bluez 
# linux redhat 7.3
# bluedialer automates bluetooth dial up from laptop to Orange

use Term::ReadKey;

# if you have a dhcp service running and you /etc/resolv.conf get clobbered
# uncomment the next line and cp your /etc/resolv.conf to /etc/resolv.conf.orig
# and add the service DNS addresses you get when connecting through GPRS

#`cp /etc/resolv.conf.orig /etc/resolv.conf`;

# clear default route - incase I've connected somewhere else before
# pppd will add a default route but not override and existing one.
`/sbin/route del default`;
# restart bluetooth support ala redhat
`/etc/init.d/bluetooth restart`;

# set my bluetooth phone address
# change it for your one!
# I'd rather use hcitool inq - but it wont work for me.
$bdaddr="00:0A:D9:14:2B:35";

# discover if its up and what the channel number is
@disc=`sdptool browse $bdaddr`;
if (@disc < 2){print "$disc[0]\nSwitch Phone Bluetooth on ??\n";exit (-1);}
$ch=0;$ro=0;
foreach $line(@disc){
  if($line=~ /Channel/){$chan[$ch]=$line;$ch++;}
  if($line=~ /Service Name/){$name[$ro]=$line;$ro++;}
}
$co=0;
foreach $line(@name){
  if($line=~ /Dial-up Networking/){$channel=$chan[$co];}
  $co++;
}
$channel=~ s/^\s+Channel: (\d+)/$1/;
print "Channel is $channel\n";

# associate the rfcomm channel for dialup
print "Info: rfcomm connect 1 $bdaddr $channel\n";
if($pid=fork){
  print "launched rfcomm as pid number $pid\n";
  }
elsif(defined $pid){
  exec "rfcomm connect 1 $bdaddr $channel";
  }
else {
  die "Failed to fork rfcomm: $!\n";
  }
$rfcomm_pid=$pid;
sleep 3;

# kick off the pppd  
print "Info: pppd startup \n";
if($pid=fork){
  print "launched pppd as pid number $pid\n";
  }
elsif(defined $pid){
  exec "pppd call p800 debug nodetach";
  }
else {
  die "Failed to fork pppd: $!\n";
  }

# all done enter a loop waiting for the quit key 'q'
print "\aComplete - Press q to quit\n";
ReadMode('cbreak');
while(1){

if (defined ($char = ReadKey (-1))){
  if($char eq 'q'){
    # yes quit - so kill off two chile processes and set keyboard mode
    # back to normal.
    `kill $pid`;
    `kill $rfcomm_pid`;
    ReadMode('normal');
    print "\aClosed at User request\n";
    exit(0);
    }
  }
  # pause in the loop
  sleep 1;
}
