# Copyright (c) 2024 Advanced Micro Devices, Inc.
#
# SPDX-License-Identifier: Apache-2.0

proc boot_jtag { } {
	# switch to JTAG boot mode #
	targets -set -filter {name =~ "PSU*"}
	stop
	# update multiboot to ZERO
	mwr 0xffca0010 0x0
	# change boot mode to JTAG
	mwr 0xff5e0200 0x0100
	# reset
	rst -system
}

proc load_image args  {
	set elf_file [lindex $args 0]
	set bitfile [lindex $args 1]
	set fsblelf_file [lindex $args 2]

	if { [info exists ::env(HW_SERVER_URL)] } {
		connect -url $::env(HW_SERVER_URL)
	} else {
		connect
	}

	after 2000

	# setup jtag boot mode
	boot_jtag
	after 2000

	targets -set -nocase -filter {name =~ "*R5*#0"}

	# load bitstream if passed
	if { [string length $bitfile] != 0 } {
		fpga -f $bitfile -no-revision-check
	}

	rst -proc

	# load FSBL if passed
	if { [string length $fsblelf_file] != 0 } {
		dow $fsblelf_file
		after 1000
		con
		after 1000
		stop
	}

	after 2000
	dow $elf_file
	con
	exit
}

switch $argc {
	"1" {
		set zephyr_elf [lindex $argv 0]
		set bitstream ""
		set fsbl_elf ""
	}
	"2" {
		set par [lindex $argv 1]
		set substring "*.bit"
		if { [string match -nocase $substring $par] == 0 } {
			set bitstream ""
			set fsbl_elf $par
		} else {
			set bitstream $par
			set fsbl_elf ""
		}
		set zephyr_elf [lindex $argv 0]
	}
	"3" {
		set zephyr_elf [lindex $argv 0]
		set bitstream [lindex $argv 1]
		set fsbl_elf [lindex $argv 2]
	}
	default {
		puts "Unsifficient number for args"
		exit -1
	}
}

load_image "$zephyr_elf" "$bitstream" "$fsbl_elf"
