##
# Load files needed by the scenario via iPXE/HTTP
#
# \param --load-ipxe-base-dir       base directory of iPXE/HTTP server
# \param --load-ipxe-boot-dir       boot directory relative to HTTP base
# \param --load-ipxe-lighttpd       run lighttpd automatically
# \param --load-ipxe-lighttpd-port  TCP port to run lighttpd on
#

source [genode_dir]/tool/run/load.inc
source [genode_dir]/tool/run/load/pxe.inc


##
# The files are loaded implicitly via iPXE/HTTP to the target machine
#
proc run_load { } {
	global load_spawn_id
	set load_spawn_id -1
	return true
}


proc load_ipxe_base_dir { } { return [get_cmd_arg --load-ipxe-base-dir ""] }


proc load_ipxe_boot_dir { } { return [get_cmd_arg --load-ipxe-boot-dir ""] }


proc load_ipxe_lighttpd { } { return [get_cmd_switch --load-ipxe-lighttpd] }


proc load_ipxe_lighttpd_port { } { return [get_cmd_arg --load-ipxe-lighttpd-port 8080] }


proc image_extension { } {
	if {[have_include "image/iso"]} {
		return "iso"
	} elseif {[have_include "image/uefi"]} {
		return "img"
	} else {
		puts "Warning, iPXE requires ISO or UEFI image."
		exit -1
	}
}


##
# Install files needed to boot via iPXE
#
proc install_bender_to_run_dir { } {
	exec mkdir -p [run_dir]/boot
	exec cp [genode_dir]/tool/boot/bender [run_dir]/boot/bender
}


##
# Create symlink for ISO image in current run directory.
#
proc create_symlink_for_iso { } {
	exec ln -sfn [pwd]/[run_dir].[image_extension] [pwd]/[run_dir]/[run_name].[image_extension]
}

##
# Update iPXE boot directory to point to current run directory.
#
proc update_ipxe_boot_dir { } {
	exec ln -sfn [pwd]/[run_dir] [load_ipxe_base_dir]/[load_ipxe_boot_dir]
}

##
# Create iPXE config file which directly boots an image file.
#
# Note, the sanboot URI works relative to the script path and honors the former
# protocol too (which must be http:// not tftp://)
#
proc create_ipxe_config { } {
	set fh [open "[run_dir]/boot.cfg" "WRONLY CREAT TRUNC"]
	puts $fh "#!ipxe"
	puts $fh "sanboot [run_name].[image_extension] || goto failed"
	puts $fh ""
	puts $fh ":failed"
	puts $fh "echo Booting failed, dropping to shell"
	puts $fh "shell"
	puts $fh "boot"
	close $fh

	if {![load_ipxe_lighttpd]} { return }

	set conf_file [file normalize [run_dir]/lighttpd.conf]

	set fh [open "$conf_file" "WRONLY CREAT TRUNC"]
	puts $fh "server.port          = [load_ipxe_lighttpd_port]"
	puts $fh "server.document-root = \"[file normalize [run_dir]]\""
	puts $fh "server.errorlog      = \"/dev/null\""
	close $fh

	global lighttpd_spawn_id
	spawn [installed_command lighttpd] -f $conf_file -D
	set lighttpd_spawn_id $spawn_id
}


# Override the exit procedure
rename exit load_ipxe_real_exit
proc exit {{status 0}} {
	if {[load_ipxe_lighttpd]} {
		global lighttpd_spawn_id
		# variable may not exist if the script fails early
		if {[info exists lighttpd_spawn_id]} { kill_spawned $lighttpd_spawn_id }
	}

	load_ipxe_real_exit $status
}
