#
# Copyright (C) 2016 Jiang Yutang <jiangyutang1978@gmail.com>
# Copyright (C) 2025 Pawel Dembicki <paweldembicki@gmail.com>
#
# This is free software, licensed under the GNU General Public License v2.
# See /LICENSE for more information.
#

include $(TOPDIR)/rules.mk

PKG_VERSION:=2025.01
PKG_HASH:=cdef7d507c93f1bbd9f015ea9bc21fa074268481405501945abc6f854d5b686f
PKG_RELEASE:=1

include $(INCLUDE_DIR)/u-boot.mk
include $(INCLUDE_DIR)/package.mk

TOOLCHAIN_NAME:=openwrt-toolchain-24.10.4-mpc85xx-p2020_gcc-13.3.0_musl.Linux-x86_64
TOOLCHAIN_FILE:=$(TOOLCHAIN_NAME).tar.zst
TOOLCHAIN_PATH:=$(PKG_BUILD_DIR)/$(TOOLCHAIN_NAME)/toolchain-powerpc_8548_gcc-13.3.0_musl/bin
TOOLCHAIN_CROSS_COMPILE:=powerpc-openwrt-linux-musl-

define Download/uboot-qoriq-toolchain
  FILE:=$(TOOLCHAIN_FILE)
  URL:=https://downloads.openwrt.org/releases/24.10.4/targets/mpc85xx/p2020/
  URL_FILE:=$(TOOLCHAIN_FILE)
  HASH:=c16566bb3625b6c45e4184b9d37953d4c3c1dcdec1141a45df834da626d4c08d
endef

define U-Boot/Default
  BUILD_TARGET:=qoriq
  BUILD_SUBTARGET:=generic
  BUILD_DEVICES:=$(1)
  ENV_SIZE:=0x2000
endef

define U-Boot/fsl_T4240RDB-nor
  NAME:=NXP T4240RDB NOR Boot
  BUILD_DEVICES:=fsl_T4240RDB
  UBOOT_CONFIG:=T4240RDB
  UBOOT_IMAGE:=u-boot-dtb.bin
endef

define U-Boot/fsl_T4240RDB-sdboot
  NAME:=NXP T4240RDB SD Card Boot
  BUILD_DEVICES:=fsl_T4240RDB
  UBOOT_CONFIG:=T4240RDB_SDCARD
  UBOOT_IMAGE:=u-boot-with-spl-pbl.bin
endef

UBOOT_TARGETS := \
  fsl_T4240RDB-nor \
  fsl_T4240RDB-sdboot

define Build/Prepare
		$(Build/Prepare/Default)
	$(TAR) -I $(STAGING_DIR_HOST)/bin/zstd -xf $(DL_DIR)/$(TOOLCHAIN_FILE) -C $(PKG_BUILD_DIR)/
endef

define Build/Compile/U-Boot
	+$(MAKE) $(PKG_JOBS) -C $(PKG_BUILD_DIR) \
		CROSS_COMPILE=$(TOOLCHAIN_PATH)/$(TOOLCHAIN_CROSS_COMPILE) \
		$(if $(DTC),DTC="$(DTC)") \
		$(UBOOT_MAKE_FLAGS)
endef

define Build/InstallDev
	$(INSTALL_DIR) $(STAGING_DIR_IMAGE)
	$(INSTALL_DATA) $(PKG_BUILD_DIR)/$(UBOOT_IMAGE) \
		$(STAGING_DIR_IMAGE)/$(BUILD_VARIANT)-uboot.bin
	$(PKG_BUILD_DIR)/tools/mkenvimage -b -s $(ENV_SIZE) \
		-o $(STAGING_DIR_IMAGE)/$(BUILD_VARIANT)-uboot-env.bin \
		files/$(BUILD_VARIANT)-uEnv.txt
endef

define Package/u-boot/install/default
endef

$(eval $(call Download,uboot-qoriq-toolchain))
$(eval $(call BuildPackage/U-Boot))
