#!/usr/bin/env bash

SCRIPT_DIR="$(dirname $0)"
BOARD_DIR="${SCRIPT_DIR}/board/raspmx"
GENIMAGE_CFG="${BOARD_DIR}/genimage.cfg"
GENIMAGE_TMP="${BUILD_DIR}/genimage.tmp"

mkdir -p ${BOARD_DIR}

${HOST_DIR}/usr/bin/mkimage -A arm -O linux -T ramdisk -C gzip  \
-n "Ramdisk Image" -d ${BINARIES_DIR}/rootfs.ext4.gz ${BINARIES_DIR}/urootfs.ext4.gz

## prepare the contents of the FAT partition to load rootfs from the ramdisk file on SD
install -D ${BOARD_DIR}/boot.scr.fat ${BINARIES_DIR}/SD_contents/boot/boot.scr
install -D ${BINARIES_DIR}/zImage ${BINARIES_DIR}/SD_contents/boot/zImage
#install -D ${BINARIES_DIR}/rootfs.ext4.gz ${BINARIES_DIR}/SD_contents/boot/rootfs.ext4.gz
install -D ${BINARIES_DIR}/urootfs.ext4.gz ${BINARIES_DIR}/SD_contents/boot/rootfs.ext4.gz
install -D ${BINARIES_DIR}/rasp-mx.dtb ${BINARIES_DIR}/SD_contents/boot/rasp-mx.dtb

## prepare an SD card dumped image to load rootfs from native ext4 partition on SD
# create genimage.cfg
(
  echo '# Minimal SD card image for the RASP-MX'
  echo '#'
  echo '# The SD card must have at least 1 MB free at the beginning.'
  echo '# U-Boot and its environment are dumped as is.'
  echo '# A single root filesystem partition is required (Ext4 in this case).'
  echo ''
  echo 'image sdcard.img {'
  echo '  hdimage {'
  echo '  }'
  echo ''
  echo '  partition spl {'
  echo '    in-partition-table = "no"'
  echo '    image = "SPL"'
  echo '    offset = 1024'
  echo '  }'
  echo ''
  echo '  partition u-boot {'
  echo '    in-partition-table = "no"'
  echo '    image = "u-boot.img"'
  echo '    offset = 70656'
  echo '  }'
  echo ''
  echo '  partition rootfs {'
  echo '    partition-type = 0x83'
  echo '    image = "rootfs.ext4"'
  echo '    size = 512M'
  echo '  }'
  echo '}'
) > ${GENIMAGE_CFG}

# add missing symbolic link
(cd ${BINARIES_DIR}; ln -sf rootfs.ext2 rootfs.ext4)

# clean workspace
rm -rf "${GENIMAGE_TMP}"

# generate image
genimage \
  --rootpath "${TARGET_DIR}" \
  --tmppath "${GENIMAGE_TMP}" \
  --inputpath "${BINARIES_DIR}" \
  --outputpath "${BINARIES_DIR}" \
  --config "${GENIMAGE_CFG}"

