#!/bin/sh -e

BL2_BLOCK_SIZE=524288
TPL_BLOCK_SIZE=2097152
UBOOT_FILE=/usr/share/factory-tool/files/u-boot-signed.bin
set -eo pipefail

eb_size() {
  mtdinfo "$1" | grep 'Eraseblock size' | egrep -o '[0-9]+ *bytes' | tr -cd 0-9
}

if ! [ -e "$UBOOT_FILE" ]; then
  echo "Error: missing $UBOOT_FILE, either deleted or an unsigned build used."
  exit 1
fi

eraseBlockSizeMtd0=`eb_size /dev/mtd0`
eraseBlockSizeMtd1=`eb_size /dev/mtd1`
eraseCountMtd0=$((BL2_BLOCK_SIZE/eraseBlockSizeMtd0))
eraseCountMtd1=$((TPL_BLOCK_SIZE/eraseBlockSizeMtd1))

check1=$((eraseCountMtd0*eraseBlockSizeMtd0 == BL2_BLOCK_SIZE))
check2=$((eraseCountMtd1*eraseBlockSizeMtd1 == TPL_BLOCK_SIZE))

if ! [ "$check1" = 1 -a "$check2" = 1 ]; then
  echo "Invalid erase block size: mtd0: $eraseCountMtd0, mtd1: $eraseCountMtd1"
  exit 1
fi

for i in 0 1; do
  flash_erase /dev/mtd0 $((BL2_BLOCK_SIZE*i)) $eraseCountMtd0
  nandwrite --input-size 49152 /dev/mtd0 "$UBOOT_FILE" -s $((BL2_BLOCK_SIZE*i))
  flash_erase /dev/mtd1 $((TPL_BLOCK_SIZE*i)) $eraseCountMtd1
  nandwrite --input-skip 49152 -p /dev/mtd1 "$UBOOT_FILE" -s $((TPL_BLOCK_SIZE*$i))
done

echo
echo "Flashing u-boot successful!"
