##
# Get the output of the target machine via serial connection
#
# \param --log-serial-cmd    Cmd that is executed to capture the output
# \param --log-serial-filter Sanitize output by piping it through a filter
#

source [genode_dir]/tool/run/log.inc


set default_serial_cmd "picocom -b 115200 /dev/ttyUSB0"


proc log_serial_cmd { } {
	global default_serial_cmd
	return [get_cmd_arg --log-serial-cmd $default_serial_cmd]
}


proc log_serial_filter { } {
	return [get_cmd_arg --log-serial-filter ""]
}


##
# Log output of the test machine via serial device
#
proc run_log { wait_for_re timeout_value } {
	global output_spawn_id

	set kernel_msg [run_boot_string]

	#
	# Certain devices send garbage through the serial connection that may
	# result in an unexpected EOF in expect. This is caused by TCL using the
	# terminal encoding for the channel to the spawned program and interpreting
	# the input for conversion to UTF-8. In the case of the serial connection,
	# this may not be valid with garbage bytes in the character stream. If any
	# garbage coming from the serial connection is interpreted as the beginning
	# of a UTF-8 multi-byte sequence but does not resemble the complete
	# sequence (i.e., is truncated), parsing may result in EOF. To prevent this
	# from happening one may use a filter that sanitizes the serial output,
	# i.e., lets only ASCII characters through.
	#
	set serial_cmd_chain [log_serial_cmd]
	if {[get_cmd_switch --log-serial-filter]} {
		set serial_cmd_chain "$serial_cmd_chain | [log_serial_filter]"
	}

	#
	# XXX the initial timeout was estimated by testing and is merely enough
	#     to load large scenarios via TFTP.
	#
	set timeout 210

	spawn /bin/sh -c "$serial_cmd_chain"
	set output_spawn_id $spawn_id

	expect {
		-i $output_spawn_id $kernel_msg { }
		eof         {
			puts stderr "Aborting, received EOF"
			return false
		}
		timeout     {
			puts stderr "Boot process timed out"
			close
			return false
		}
	}

	wait_for_output $wait_for_re $timeout_value $output_spawn_id
	return true
}
