#!/usr/bin/expect -f
#
# Routing through Kernel AX.25
#

# --------------------- User configurable ---------------------
set digi db0aab-1
set axport 438
set l2_timeout 10
set l3_timeout 60
set destination "unknown"
# --------------------- User configurable ---------------------

set timeout 10
log_user 0

#
# Just for debugging
#

proc syslog {msg} {

# To put something into the log

	global destination
        set filename "$destination script"
        exec logger -p local5.info "$filename (pid=[pid]): $msg"
}

set con_ctl $user_spawn_id
set con_ctl_pid [pid]

# Read the destination from con_ctl. It writes to us something like:
#
#       connect ax25 db0bcc
#
expect timeout {
	syslog "timed out waiting for connect command"
	exit 1
} -re "(connect ax25 .*)\n"
set destination [ lindex $expect_out(0,string) 2 ]

# Start `call' in raw mode (-r)
# It is essential not to echo back anything coming from within clx.
# Otherwise the log will contain every message twice (<- and ->) and 
# maybe other strange things will happen.
set stty_init "-echo"
spawn /usr/bin/call -r $axport $digi

# remember spawn_id and pid
set call $spawn_id
set call_pid [exp_pid -i $call]

# Wait for the L2 connect
syslog "Starting connect to $destination (call pid=$call_pid)"
set timeout $l2_timeout
expect timeout {
	syslog "timed out waiting for L2 connect"
	exit 1
	} -re "\[Cc]onnected to \[^\r]*\r\n"

# Now wait for the L3 connect
send "c $destination\n"
set timeout $l3_timeout
expect timeout { 
	syslog "timed out waiting for L3 connect"
	exit 1
	} -re "\[Cc]onnected to \[^\r]*\r\n"
syslog "connected to $destination (call pid=$call_pid)"


# We succeeded! Now relay everything from $con_ctl to $call and 
# vice versa until an eof is received from call or until con_ctl
# terminates us. The "\3" is just there so you can test out the
# script manually and finish it by pressing ctrl-C. Normally, the
# program switches the terminal into raw mode and simply relays
# everything and you cannot even send a ctrl-C or ctrl-Z.
# This makes interact to finish on seeing a ctrl-C. Hopefully,
# we will never have to transmit this character.

interact "\3" {
		syslog "ctrl-C pressed - exiting"
		exit
	}
syslog "eof rcvd from /usr/bin/call - exiting"
exit

