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

. config/options ""

mkimage_uboot(){
  echo "image: writing u-boot to $(basename $DISK)"
  dd if="$INSTALL/usr/share/bootloader/u-boot.bin.sd.bin" of="$DISK" conv=fsync,notrunc bs=1 count=440 >"$SAVE_ERROR" 2>&1 || show_error
  dd if="$INSTALL/usr/share/bootloader/u-boot.bin.sd.bin" of="$DISK" conv=fsync,notrunc bs=512 skip=1 seek=1 >"$SAVE_ERROR" 2>&1 || show_error
}

mkimage_autoscripts(){
  echo "image: copying autoscript files"
  mcopy -s -o ${RELEASE_DIR}/3rdparty/bootloader/*script ::
  mcopy -s -o ${RELEASE_DIR}/3rdparty/bootloader/*.scr ::
  touch "$RELEASE_DIR/3rdparty/bootloader/aml_autoscript.zip"
}

mkimage_bootini(){
  if [ -f ${RELEASE_DIR}/3rdparty/bootloader/boot.ini ]; then
    echo "image: copying boot.ini"
    mcopy -s -o ${RELEASE_DIR}/3rdparty/bootloader/boot.ini ::
  fi
}

mkimage_uEnv(){
  echo "image: creating uEnv.ini"
cat << EOF > "${LE_TMP}/uEnv.ini"
dtb_name=/amlogic/${DTB}
bootargs=boot=UUID=${UUID_SYSTEM} disk=UUID=${UUID_STORAGE} quiet ${EXTRA_CMDLINE}
EOF
  mcopy -s "${LE_TMP}/uEnv.ini" ::
}

mkimage_extlinux(){
  echo "image: copying exlinux.conf"
  mkdir -p "${LE_TMP}/extlinux"
  cat << EOF > "${LE_TMP}/extlinux/extlinux.conf"
LABEL ${DISTRO}
  LINUX /${KERNEL_NAME}
  FDT /amlogic/${DTB}
  APPEND boot=LABEL=${DISTRO_BOOTLABEL} disk=LABEL=${DISTRO_DISKLABEL} quiet ${EXTRA_CMDLINE}
EOF
  mcopy -s -o "${LE_TMP}/extlinux" ::
}

mkimage_extlinux_fdtdir(){
  echo "image: copying exlinux.conf"
  mkdir -p "${LE_TMP}/extlinux"
  cat << EOF > "${LE_TMP}/extlinux/extlinux.conf"
LABEL ${DISTRO}
  LINUX /${KERNEL_NAME}
  FDTDIR /amlogic/
  APPEND boot=LABEL=${DISTRO_BOOTLABEL} disk=LABEL=${DISTRO_DISKLABEL} quiet ${EXTRA_CMDLINE}
EOF
  mcopy -s -o "${LE_TMP}/extlinux" ::
}

mkimage_dtb(){
  echo "image: copying device trees"
  mcopy -s -o "${RELEASE_DIR}/3rdparty/bootloader/amlogic" ::
}

case "${UBOOT_SYSTEM}" in
  box|"")
    DTB="@@DTB_NAME@@"
    mkimage_uEnv
    mkimage_autoscripts
    mkimage_bootini
    mkimage_dtb
    ;;
  odroid-n2|odroid-c4)
    mkimage_uboot
    mkimage_extlinux_fdtdir
    mkimage_dtb
    ;;
  bananapi*|khadas*|lafrite|lepotato|nanopi-k2|odroid*|radxa*|wetek*)
    mkimage_uboot
    mkimage_extlinux
    mkimage_dtb
    ;;
  *)
    mkimage_uEnv
    mkimage_autoscripts
    mkimage_bootini
    mkimage_extlinux
    mkimage_uboot
    mkimage_dtb
    ;;
esac
