#
# \brief  Codezero-specific test-environment supplements
# \author Norman Feske
# \date   2011-08-05
#
# This file is meant to be used as '--include' argument for 'tool/run'.
#


##
# Return location of prebuilt mirror of codezero source tree
#
proc kernel_dir { } { return [pwd]/kernel/codezero }


##
# Return container directory where the Genode binaries should be copied to
#
proc container_dir { } { return [kernel_dir]/build/cont0/empty0 }


##
# Return location of 'gen_romfs' tool
#
proc gen_romfs { } { return "[genode_dir]/base-codezero/tool/gen_romfs" }


##
# Print and execute shell command
#
proc exec_sh { command } {
	puts "$command"
	exec sh -c $command
}


##################################
## Test framework API functions ##
##################################

proc create_boot_directory { } {

	# create only intermediate directries hosting the run directory
	exec mkdir -p [run_dir]
	exec rm -rf [run_dir]

	exec mkdir -p [run_dir]/genode
}


proc build_boot_image {binaries} {

	if {![file exists kernel]} { build kernel }

	copy_and_strip_genode_binaries_to_run_dir $binaries

	# the codezero build system expects that the pager binary is named 'main.elf'
	exec cp [run_dir]/genode/core [container_dir]/main.elf

	# obtain list of modules
	set modules [glob [run_dir]/genode/*]

	# remove core from list of modules
	set core_idx [lsearch -exact $modules [run_dir]/genode/core]
	set modules [lreplace $modules $core_idx $core_idx]

	# generate elf image containing the boot modules
	exec_sh "[gen_romfs] -p [cross_dev_prefix] -c [run_dir]/genode/core -o [container_dir]/modules.elf $modules"

	set tool_chain_dir [file dirname [cross_dev_prefix]]
	set prepend_path ""
	if {[file isdirectory $tool_chain_dir]} {
		set prepend_path $tool_chain_dir }

	# force re-generation of 'cinfo.c', which depends on the container content
	exec_sh "rm -f [kernel_dir]/src/generic/cinfo.c"

	# rebuild codezero, linking the new container content
	exec_sh "cd [kernel_dir]; PATH=$prepend_path:\$PATH ./build.py"

	# copy result to [run_dir]/image.elf (to be picked up by spawn_qemu)
	exec_sh "cp [kernel_dir]/build/final.elf [run_dir]/image.elf"
}


proc run_genode_until {{wait_for_re forever} {timeout_value 0} {running_spawn_id -1}} {
	#
	# If a running_spawn_id is specified, wait for the expected output
	#
	if {$running_spawn_id != -1} {
		wait_for_output $wait_for_re $timeout_value $running_spawn_id
		return
	}

	#
	# Try to use one of the supported backends for running the scripts
	#
	if {[is_qemu_available]} {
		spawn_qemu $wait_for_re $timeout_value
		return
	}

	global run_target
	puts stderr "Error: Can't execute automatically on target '$run_target'"
	exit -1
}
