#!/bin/bash
set -e
UBOOT_ENV_SIZE=262144

cat > uboot_menu.in <<EOF
bootcmd=
  setenv bootargs
    \${bootargs_base} \${mtdparts}
    rootfstype=ext2 root=/dev/mmcblk0p2 rootdelay=5 panic=10;
  mmcinit;
  ext2load mmc 1 0x32000000 \${sd_image_name};
  bootm 0x32000000

menu_1=
  Boot from Flash:
  setenv bootargs
    \${bootargs_base} \${mtdparts};
  nand read.e 0x32000000 kernel 0x200000;
  bootm 0x32000000

menu_2=
  Reboot:
  reset

menu_3=
  Power off:
  neo1973 power-off

menu_4=
  Set console to USB:
  setenv stdin usbtty;
  setenv stdout usbtty;
  setenv stderr usbtty

menu_5=
  Set console to serial:
  setenv stdin serial;
  setenv stdout serial;
  setenv stderr serial

menu_6=
  SD/uImage2.bin:
  setenv bootargs
    \${bootargs_base} \${mtdparts}
    rootfstype=ext2 root=/dev/mmcblk0p2 rootdelay=5 panic=10;
  mmcinit;
  ext2load mmc 1 0x32000000 uImage2.bin;
  bootm 0x32000000

menu_7=
  SD/uImage3.bin:
  setenv bootargs
    \${bootargs_base} \${mtdparts}
    rootfstype=ext2 root=/dev/mmcblk0p2 rootdelay=5 panic=10;
  mmcinit;
  ext2load mmc 1 0x32000000 uImage3.bin;
  bootm 0x32000000

menu_8=
EOF

echo " * Checking for a sane MTD configuration"
if ! fgrep mtd2 < /proc/mtd |fgrep -q "u-boot_env"; then
    echo "E: U-Boot environment not found at expected location in mtd2"
    exit 1
fi

echo " * Dumping current U-Boot environment"
nanddump /dev/mtd2 -o -b -f env.orig
if [ ! $(wc -c env.orig | awk '{print $1}') -eq $UBOOT_ENV_SIZE ]; then
    echo "Environment did not have the expected size of $UBOOT_ENV_SIZE"
    exit 1
fi
echo " * Merging Debian menu entries into U-Boot environment (can take up to 70s)"
uboot-envedit -c -i env.orig -f uboot_menu.in -o env.new
if [ ! $(wc -c env.new | awk '{print $1}') -eq $UBOOT_ENV_SIZE ]; then
    echo "Newly created environment did not have the expected size of $UBOOT_ENV_SIZE"
    exit 1
fi
echo " * Writing back U-Boot environment"
flash_eraseall /dev/mtd2
nandwrite /dev/mtd2 env.new
