#!/usr/bin/env bash

GENIMAGE_TMP="${BUILD_DIR}/genimage.tmp"
GENIMAGE_CFG=board/cv/cv_octavo_produktion/genimage.cfg

if [ -e ${BASE_DIR}/cv_octavo_std_bindir.sh ]
then
	source ${BASE_DIR}/cv_octavo_std_bindir.sh
fi

echo Standard BinDir: $CV_OCTAVO_STANDARD_BINDIR

if [ -e ${BASE_DIR}/copyImages.sh ]
then
	${BASE_DIR}/copyImages.sh $CV_OCTAVO_STANDARD_BINDIR
fi

if [ -n "$CV_OCTAVO_STANDARD_BINDIR" ]; then
	cp $CV_OCTAVO_STANDARD_BINDIR/MLO $BINARIES_DIR/STANDARD_MLO
    cp $CV_OCTAVO_STANDARD_BINDIR/rootfs.ubi $BINARIES_DIR/STANDARD_rootfs.ubi
    cp $CV_OCTAVO_STANDARD_BINDIR/u-boot.img $BINARIES_DIR/STANDARD_u-boot.img
    cp $CV_OCTAVO_STANDARD_BINDIR/uImage.CV_34_39_500A $BINARIES_DIR/STANDARD_uImage.CV_34_39_500A
    cp $CV_OCTAVO_STANDARD_BINDIR/uImage.CV_34_39_500B $BINARIES_DIR/STANDARD_uImage.CV_34_39_500B
    cp $CV_OCTAVO_STANDARD_BINDIR/uImage.CV_34_39_500B_KiTi $BINARIES_DIR/STANDARD_uImage.CV_34_39_500B_KiTi
    cp $CV_OCTAVO_STANDARD_BINDIR/uImage.CV_34_39_500B_BM $BINARIES_DIR/STANDARD_uImage.CV_34_39_500B_BM
    if [ -e ${BASE_DIR}/old.sh ]
	then
		GENIMAGE_CFG=board/cv/cv_octavo_produktion/genimage_complete_old.cfg
	else
    	GENIMAGE_CFG=board/cv/cv_octavo_produktion/genimage_complete.cfg
   	fi
fi

if [ -e ${BASE_DIR}/copyImages.sh ]
then
	${BASE_DIR}/copyImages.sh $BINARIES_DIR
fi

# Pass an empty rootpath. genimage makes a full copy of the given rootpath to
# ${GENIMAGE_TMP}/root so passing TARGET_DIR would be a waste of time and disk
# space. We don't rely on genimage to build the rootfs image, just to insert a
# pre-built one in the disk image.

trap 'rm -rf "${ROOTPATH_TMP}"' EXIT
ROOTPATH_TMP="$(mktemp -d)"

rm -rf "${GENIMAGE_TMP}"

genimage \
	--rootpath "${ROOTPATH_TMP}"     \
	--tmppath "${GENIMAGE_TMP}"    \
	--inputpath "${BINARIES_DIR}"  \
	--outputpath "${BINARIES_DIR}" \
	--config "${GENIMAGE_CFG}"
