#!/usr/bin/perl
$ENV{'PATH'} = '/bin:/usr/bin';

# If your machine does IP forwarding and you want to connect the Palm to
# a remote machine, set $remoteip to an unused address on your subnet.
# You may have to add "proxyarp" to the ppd command line, too.  Otherwise,
# set it to a reserved IP address from the ranges:
#	10.0.0.0-10.255.255.255
#	172.16.0.0-172.31.255.255
#	192.168.0.0-192.168.255.255
# Enable IP masquerading for the address, eg:
#	ipfwadm -F -p deny
#	ipfwadm -F -a accept -m -S $remoteip

$remoteip = '10.0.0.1';

# IP address of the machine this runs on
$localip  = `host \$VH | sed 's/.* //; q'`; chop $localip;
$dev	  = '/dev/pilot';	# read+write permissions required on device
$speed	  = 57600;		# same as the Palm's modem speed setting
				# and no higher than serial port's max speed
$sleep	  = 1;			# 2 is probably safer
$pppd	  = '/usr/sbin/pppd';

# palmppp - run a PPP Internet session for a Palm on a serial connection
# Matt Welsh, mdw@cs.berkeley.edu
# Steve Kinzler, steve@kinzler.com, Mar 00
# https://kinzler.com/me/home.html#palm
# adapted from http://www.cs.berkeley.edu/~mdw/proj/ninja/pilot/ppup
# see also http://www.cs.berkeley.edu/~mdw/proj/ninja/pilot/pilot-ppp.html

$usage   = "usage: $0 [ local-ip-addr ]\n";
die $usage if $#ARGV > 0 || $ARGV[0] eq '-h';

$localip = shift @ARGV if @ARGV;
die "$0: no local-ip-addr\n" unless $localip;

system("stty $speed sane < $dev");
open(STDIN,  "+<$dev")   or die "$0: cannot open $dev ($!)";
open(STDOUT, '+<&STDIN') or die "$0: cannot dup STDIN ($!)";
$| = 1;

print STDERR "Press the Network Connect button on the Palm\n";

while (<STDIN>) {		# works with a "Standard" modem
	next unless /AT/i;
	if (/DT/i) {
		print "\nRINGING\n"; sleep $sleep;
		print "\nRINGING\n"; sleep $sleep;
		print "\nCONNECT $speed\n\n";
		print STDERR "Connecting\n";
		exec "$pppd local $speed crtscts debug $localip:$remoteip"
			or die "$0: cannot exec $pppd ($!)";
	}
	print "\nOK\n";
}
