#!/usr/bin/expect -f
#
# Routing through TNT
#

# --------------------- User configurable ---------------------
set digi db0aab-1
set telnet_timeout 10
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]
set exp_disconnected 1

# 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 ]

# 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/telnet localhost 4718

# remember spawn_id and pid
set telnet $spawn_id
set telnet_pid [exp_pid -i $telnet]

# Wait for the L2 connect
syslog "Starting connect to localhost)"
set timeout $telnet_timeout
expect timeout {
	syslog "timed out waiting for telnet connect"
	exit 1
	} -re "\[Cc]onnected to \[^\n]*\n"

# Now wait for the L2 connect
send "conn ax25 $digi\n"
set timeout $l2_timeout
expect timeout { 
	syslog "timed out waiting for L2 connect"
	exit 1
	} "=>"
syslog "connected to $digi (telnet pid=$telnet_pid)"

# 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 (telnet pid=$telnet_pid)"


# We succeeded! Now relay everything from $con_ctl to $telnet and 
# vice versa until an eof is received from telnet 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.

syslog "connecting $spawn_id with $con_ctl"
# stty -echo
interact "\3" {
	syslog "ctrl-C pressed - exiting"
	exit
}

syslog "eof rcvd from /usr/bin/telnet - exiting"
exit

