#!/bin/sh
MAC=""
SDK=`bootblocktool -x SDK`
if [ "$1" != "rw" ] ; then
  # boot block
  if [ "$1" = "all" ] ; then
    MAC=$2
    ./flash_erase /dev/mtd0 0 2
    ./nandwrite /dev/mtd0 ${3}/part0.img -s 0
    if [ "$MAC" != "" ] ; then
        ./bootblocktool -w SERNO=$MAC
    fi
    ./bootblocktool -w SDK=2.10
  fi
  if [ "$1" = "update" ] && [ "$SDK" != "2.10" ] ; then
    MAC=`bootblocktool -x SERNO`
    ./flash_erase /dev/mtd0 0 2
    ./nandwrite /dev/mtd0 ${3}/part0.img -s 0
    if [ "$MAC" != "" ] ; then
        ./bootblocktool -w SERNO=$MAC
    fi
    ./bootblocktool -w SDK=2.10
  fi
  ./flash_erase /dev/mtd0 0x40000 894
  # kernel
  ./nandwrite /dev/mtd0 ${3}/part1.img -s 0x0040000
  # rootfs
  ./nandwrite /dev/mtd0 ${3}/part2.img -s 0x800000
  # rwfs
  ./nandwrite /dev/mtd0 ${3}/part3.img -s 0x2000000
else
  # use images from RW flash partition
  # copy bootblock (only if there is no previous image, when we decide that previous try fail) before reflash, and erase
  if [ ! -f "/mnt/.store/part0.img" ] ; then
    ./nanddump -s 0 -l 131072 -o -b -f /mnt/.store/part0.img /dev/mtd0
    ./sync
  fi
  ./mount -r -o remount /mnt/.store
  ./flash_erase /dev/mtd0 0 2
  echo "copy part3.img to the RAM"
  ./ls -l /mnt/flash/.images/part3.img
  ./cp /mnt/flash/.images/part3.img /tmp/part3.img
  ./ls -l /mnt/flash/.images/part3.img
  ./ls -l /tmp/part3.img
  # rootfs
  echo "part2.img"
  ./ls -l /mnt/flash/.images/part2.img
  ./flash_erase /dev/mtd0 0x800000 192
  ./ls -l /mnt/flash/.images/part2.img
  ./nandwrite /dev/mtd0 /mnt/flash/.images/part2.img -s 0x800000
  # kernel
  echo "part1.img"
  ./ls -l /mnt/flash/.images/part1.img
  ./flash_erase /dev/mtd0 0x0040000 62
  ./ls -l /mnt/flash/.images/part1.img
  ./nandwrite /dev/mtd0 /mnt/flash/.images/part1.img -s 0x0040000
  # rwfs
  echo "part3.img"
  ./ls -l /tmp/part3.img
  ./flash_erase /dev/mtd0 0x2000000 640
  ./nandwrite /dev/mtd0 /tmp/part3.img -s 0x2000000
  # restore bootblock
  echo "restore bootblock"
  ./nandwrite /dev/mtd0 /mnt/.store/part0.img -s 0
  ./mount -w -o remount /mnt/.store
  ./rm /mnt/.store/part0.img
  ./sync
  ./mount -r -o remount /mnt/.store
fi
