# SPDX-License-Identifier: GPL-2.0
# Copyright (C) 2017-present Team LibreELEC (https://libreelec.tv)

PKG_RKBIN="$(get_build_dir rkbin)"
PKG_SOC="${DEVICE/RK/rk}"

case "${PKG_SOC}" in
  rk3036)
    PKG_DATAFILE="spl/u-boot-spl-nodtb.bin"
    PKG_LOADER="u-boot-dtb.bin"
    ;;
  rk3288)
    PKG_DATAFILE="${PKG_RKBIN}/rk32/rk3288_ddr_400MHz_v1.08.bin"
    PKG_LOADER="${PKG_RKBIN}/rk32/rk3288_miniloader_v2.58.bin"
    PKG_LOAD_ADDR="0x0"
    ;;
  rk3328)
    PKG_DATAFILE="${PKG_RKBIN}/rk33/rk3328_ddr_786MHz_v1.16.bin"
    PKG_LOADER="${PKG_RKBIN}/rk33/rk3328_miniloader_v2.50.bin"
    PKG_BL31="${PKG_RKBIN}/rk33/rk3328_bl31_v1.42.elf"
    PKG_BL31_ADDR="0x10000"
    PKG_LOAD_ADDR="0x200000"
    ;;
  rk3399)
    PKG_DATAFILE="${PKG_RKBIN}/rk33/rk3399_ddr_800MHz_v1.24.bin"
    PKG_LOADER="${PKG_RKBIN}/rk33/rk3399_miniloader_v1.24.bin"
    PKG_BL31="${PKG_RKBIN}/rk33/rk3399_bl31_v1.31.elf"
    PKG_BL31_ADDR="0x40000"
    PKG_LOAD_ADDR="0x200000"
    ;;
  *)
    PKG_DATAFILE="spl/u-boot-spl-dtb.bin"
    PKG_LOADER="u-boot-dtb.bin"
    ;;
esac

if [ -n "${PKG_DATAFILE}" -a -n "${PKG_LOADER}" ]; then
  tools/mkimage -n ${PKG_SOC} -T rksd -d "${PKG_DATAFILE}" idbloader.img
  cat "${PKG_LOADER}" >> idbloader.img
  cp -av idbloader.img ${INSTALL}/usr/share/bootloader
fi

if [ -n "${PKG_LOAD_ADDR}" ]; then
  ${PKG_RKBIN}/tools/loaderimage --pack --uboot u-boot-dtb.bin uboot.img ${PKG_LOAD_ADDR}
  cp -av uboot.img ${INSTALL}/usr/share/bootloader
fi

if [ -n "${PKG_BL31}" ]; then
  cat >trust.ini <<EOF
[BL30_OPTION]
SEC=0
[BL31_OPTION]
SEC=1
PATH=${PKG_BL31}
ADDR=${PKG_BL31_ADDR}
[BL32_OPTION]
SEC=0
[BL33_OPTION]
SEC=0
[OUTPUT]
PATH=trust.img
EOF
  ${PKG_RKBIN}/tools/trust_merger --verbose trust.ini
  cp -av trust.img ${INSTALL}/usr/share/bootloader
fi
