#!/bin/bash

IMAGE_DIR=./out
NANDINFO_NNI=$IMAGE_DIR/NANDINFO.nni
PAIRPAGEMAP_V2_PPM=$IMAGE_DIR/PAIRPAGEMAP_v2.ppm
PARTITION_V2_DEFAULT_PNI=$IMAGE_DIR/PARTITION_v2_default.pni
MBOOT_BIN=$IMAGE_DIR/mboot.bin
ROMBOOT_BIN=$IMAGE_DIR/RomBoot.bin
PADDED_BIN=$IMAGE_DIR/padded.bin
HASH0_BIN=$IMAGE_DIR/HASH0_DAT.bin

NANDINFO_NNI_SIZE=$(stat -c%s $NANDINFO_NNI)
PAIRPAGEMAP_V2_PPM_SIZE=$(stat -c%s $PAIRPAGEMAP_V2_PPM)
PARTITION_V2_DEFAULT_PNI_SIZE=$(stat -c%s $PARTITION_V2_DEFAULT_PNI)
MBOOT_BIN_SIZE=$(stat -c%s $MBOOT_BIN)
HASH0_BIN_SIZE=$(stat -c%s $HASH0_BIN)

echo "$NANDINFO_NNI file size : $NANDINFO_NNI_SIZE"

PADDED_SIZE=$(($NANDINFO_NNI_SIZE-($NANDINFO_NNI_SIZE&0xFFF0000)))

if [ $PADDED_SIZE!=0 ]; then
	PADDED_SIZE=$((0x10000-$PADDED_SIZE))
fi

cat "$NANDINFO_NNI" >$ROMBOOT_BIN

echo "$NANDINFO_NNI"" (NANDINFO_NNI) padding size : $PADDED_SIZE"

if [ $PADDED_SIZE!=0 ]; then
	dd if=/dev/zero bs=1 count=$PADDED_SIZE | tr "\000" "\377" > $PADDED_BIN
	cat $PADDED_BIN >>$ROMBOOT_BIN
	rm $PADDED_BIN
fi


echo "$PAIRPAGEMAP_V2_PPM file size : $PAIRPAGEMAP_V2_PPM_SIZE"

PADDED_SIZE=$(($PAIRPAGEMAP_V2_PPM_SIZE-($PAIRPAGEMAP_V2_PPM_SIZE&0xFFF0000)))

if [ $PADDED_SIZE!=0 ]; then
	PADDED_SIZE=$((0x10000-$PADDED_SIZE))
fi

cat "$PAIRPAGEMAP_V2_PPM" >>$ROMBOOT_BIN

echo "$PAIRPAGEMAP_V2_PPM"" (PAIRPAGEMAP_PPM) padding size : $PADDED_SIZE"

if [ $PADDED_SIZE!=0 ]; then
	dd if=/dev/zero bs=1 count=$PADDED_SIZE | tr "\000" "\377" > $PADDED_BIN
	cat $PADDED_BIN >>$ROMBOOT_BIN
	rm $PADDED_BIN
fi

echo "$PARTITION_V2_DEFAULT_PNI file size : $PARTITION_V2_DEFAULT_PNI_SIZE"

PADDED_SIZE=$(($PARTITION_V2_DEFAULT_PNI_SIZE-($PARTITION_V2_DEFAULT_PNI_SIZE&0xFFF0000)))

if [ $PADDED_SIZE!=0 ]; then
	PADDED_SIZE=$((0x10000-$PADDED_SIZE))
fi

cat "$PARTITION_V2_DEFAULT_PNI" >>$ROMBOOT_BIN

echo "$PARTITION_V2_DEFAULT_PNI"" (PARTITION_PNI) padding size : $PADDED_SIZE"

if [ $PADDED_SIZE!=0 ]; then
	dd if=/dev/zero bs=1 count=$PADDED_SIZE | tr "\000" "\377" > $PADDED_BIN
	cat $PADDED_BIN >>$ROMBOOT_BIN
	rm $PADDED_BIN
fi

echo "$HASH0_BIN file size : $HASH0_BIN_SIZE"
cat "$HASH0_BIN" >>$ROMBOOT_BIN

echo "$MBOOT_BIN file size : $MBOOT_BIN_SIZE"
cat "$MBOOT_BIN" >>$ROMBOOT_BIN