#!/usr/bin/expect -f
#
# Listening on my radio port for spots
#
# Two samples:
#
# "DX de SP3JUN:    14013.5  CT3FT         0914                          0912Z"
# "PC11^1827.0^9X4WW^ 8-Jan-1997^2227Z^SSB^OZ3PZ^OZ2DXB^H6^~"
#
# The script looks for DX spots in two formats: Either in the user
# format "DX de .." or in the PC11 format. The later is converted
# into the "DX de .." format as clx only understands that in U mode.

log_user 0
set timeout -1

set dxspot "DX de ....................................................................Z"
set pc11spot "(PC11.*)~"

# First remember my spawn_id and pid
set expect_pid [pid]
set con_ctl $user_spawn_id

# Then spawn the listen process and remember spawn_id and pid
spawn /usr/bin/listen -ar
set listen $spawn_id
set listen_pid [exp_pid -i $listen]

# A very crude way to get my parent's PID, in fact we don't need this
set x [ exec cat /proc/$expect_pid/status | grep PPid ]
set ppid [ lindex $x 1 ]

# Something nice to look at
set prompt "listen pid=$listen_pid, con_ctl ppid=$ppid"

proc syslog {msg} {

# To put something into the log

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


syslog "sucessfully started: $prompt\n"

while (1) {
	expect {
		-i $listen 
		-re $dxspot { 
			send_user "$expect_out(0,string)\n" 
		}
		-re $pc11spot { 
			set pc11 [split $expect_out(1,string) '^']
                        set freq [lindex $pc11 1]
                        set call [lindex $pc11 2]
                        set utc [lindex $pc11 4]
                        set comment [lindex $pc11 5]
                        set from [lindex $pc11 6]:
                        set fmt "DX de %-9s %8s  %-12s %-29s %6s\n"
                        send_user [format $fmt $from $freq $call $comment $utc]
		}
		eof { 
			set msg "EOF rcvd from listen (died?) - exiting\n" 
			send_user $msg
			syslog $msg
			exit 
		}
		-i $con_ctl 
		-re ".*\n" { 
			syslog "ping rcvd from con_ctl\n" 
		}
		eof { 
			set msg "EOF rcvd from con_ctl (disc?) - exiting\n"
			send_user $msg
			syslog $msg
			exit
		}
	}
}
