##
# Muen system image configuration parameters
#
# \param --image-muen-external-build  Muen system is built automatically or externally
# \param --image-muen-system          Muen system policy
# \param --image-muen-components      Muen system components
# \param --image-muen-hardware        Muen hardware specification
# \param --image-muen-platform        Muen platform specification
# \param --image-muen-gnat-path       Path to GNAT toolchain
# \param --image-muen-spark-path      Path to SPARK toolchain
#

proc muen_external { } {
	return [get_cmd_arg --image-muen-external-build "0"]
}

proc muen_system { } {
	return [get_cmd_arg --image-muen-system ""]
}
proc muen_components { } {
	return [get_cmd_arg --image-muen-components ""]
}

proc muen_hardware { } {
	return [get_cmd_arg --image-muen-hardware ""]
}

proc muen_platform { } {
	return [get_cmd_arg --image-muen-platform ""]
}

proc muen_gnat_path { } {
	return [get_cmd_arg --image-muen-gnat-path "/usr/gnat"]
}

proc muen_spark_path { } {
	return [get_cmd_arg --image-muen-spark-path "/opt/spark2014"]
}

##
# Build and integrate Muen system image
#
# \param  elf_img   ELF binary of Genode subject
#
proc run_image {elf_img} {
	if {![have_spec "muen"]} {
		puts stderr "Error: Missing SPEC muen, unsupported platform"
		exit -1
	}

	# For external Muen system integration there is nothing left to do.
	if {[muen_external]} {
		puts "build finished due to external Muen system integration"
		exit 0
	}

	#
	# Generate Muen build config file
	#
	set fh [open "[run_dir]/muen.conf" "WRONLY CREAT TRUNC"]
	puts $fh "GNAT_PATH  = [muen_gnat_path]"
	puts $fh "SPARK_PATH = [muen_spark_path]"
	puts $fh "SYSTEM     = [muen_system]"
	puts $fh "COMPONENTS = \"[muen_components]\""
	puts $fh "HARDWARE   = [muen_hardware]"
	puts $fh "PLATFORM   = [muen_platform]"
	close $fh

	#
	# Build Muen kernel
	#
	puts "using Muen system policy '[muen_system]' on platform '[muen_hardware]'"
	if {![file exists kernel]} { exec mkdir kernel }
	exec cp [run_dir]/muen.conf kernel/muen.conf
	build kernel

	# Use raw binary object for base-hw on Muen
	set bin_img "[run_dir]/[run_name].bin"
	exec [cross_dev_prefix]objcopy -O binary $elf_img $bin_img

	#
	# Package Muen system image
	#
	exec cp $bin_img "kernel/muen/policy/obj/base_hw"
	exec make -C kernel/muen/pack SYSTEM=[muen_system] HARDWARE=[muen_hardware] PLATFORM=[muen_platform]
	exec cp kernel/muen/pack/obj/muen.img "[run_dir]/image.bin"
}
