// SPDX-License-Identifier: GPL-2.0-or-later OR MIT
/*
 * Copyright (c) 2024-2026 TQ-Systems GmbH <u-boot@ew.tq-group.com>,
 * D-82229 Seefeld, Germany.
 * Author: Max Merchel
 *
 * shared mmc environment for TQ boards
 */

addmmc=
	setenv bootargs "${bootargs}"
	root=/dev/mmcblk"${mmcblkdev}"p"${mmcrootpart}" "${rootfsmode}" rootwait;

get_blockcount=
	setexpr blkc "${filesize}" + 0x1ff;
	setexpr blkc "${blkc}" / 0x200;

load_mmc=
	mmc dev "${mmcdev}"; mmc rescan;
	load mmc "${mmcdev}":"${mmcpart}" "${kernel_addr_r}" /boot/"${image}";
	load mmc "${mmcdev}":"${mmcpart}" "${fdt_addr_r}" /boot/"${fdtfile}";
	fdt address "${fdt_addr_r}";
        fdt resize 0x100000;
	for overlay in "${fdt_overlays}"; do
		load mmc "${mmcdev}":"${mmcpart}" "${fdtoverlay_addr_r}"
                        /boot/"${overlay}" && fdt apply "${fdtoverlay_addr_r}";
	done;

mmcargs=run addtty addmmc

mmcboot=
	echo "Booting from mmc ...";
	setenv bootargs && run mmcargs &&
	if run load_mmc; then
		run boot_os;
	else
		echo "ERROR: loading from mmc";
	fi;

mmcpart=2

mmc_finish_update_uboot=
	mmc write "${loadaddr}" "${update_start_blk}" "${blkc}";
	mmc dev "${mmcdev}" 0;
	setenv update_part;
	setenv update_start_blk;
	setenv blkc;

mmc_prepare_update_uboot=
	echo "Write U-Boot to mmc "${mmcdev}" ...";
	mmc dev "${mmcdev}"; mmc rescan;
	run get_blockcount;
	setenv update_start_blk "${uboot_mmc_start}";
	setenv update_part 0;

mmc_switch_part=
	mmc partconf "${mmcdev}" update_part;
	mmc dev "${mmcdev}" "${update_part}";

mmcrootpart=2

update_uboot_mmc=
	run check_ipaddr;
	if tftp "${uboot}"; then
		run mmc_prepare_update_uboot;
		if itest "${blkc}" >= "${uboot_mmc_size}"; then
			echo "ERROR: size to large ...";
			exit;
		fi;
		if itest "${mmcdev}" == "${emmc_dev}"; then
			run mmc_switch_part;
			if itest "${update_part}" > 0 ; then
				if env exists emmc_bootp_start; then
					setenv update_start_blk "${emmc_bootp_start}";
				else
					echo "ERROR: eMMC boot partition block unset";
					exit;
				fi;
			fi;
		fi;
		run mmc_finish_update_uboot;
	fi;
