#!/bin/bash -e

main()
{
    # Verification parameters
    if [ $# -ne 1 ]; then
        echo "Usage: $0 <minimum_boot_image>"
        exit 1
    fi

    which "flash_erase" >/dev/null 2>&1
    if [ $? -ne 0 ]; then
        echo "Command 'flash_erase' not found."
        exit 2
    fi

    which "nandwrite" >/dev/null 2>&1
    if [ $? -ne 0 ]; then
        echo "Command 'nandwrite' not found."
        exit 3
    fi

    min_boot_image=$1
    image_size=`du -b ${min_boot_image} | awk '{print $1}'`

    magic_mumber=`od -N4 -t x1 ${min_boot_image}|head -1|sed -e 's/0000000//g' -e 's/ //g'|tr -d '\n'`

    if [ ${magic_mumber} != "48524943" ]; then
        echo "The format of the minimum boot image is incorrect."
        echo "Please use the image file officially provided by Horizon Robotics."
        exit 4
    fi

    if [ ! -f "/proc/mtd" ]; then
        echo "NAND flash partition file \"/proc/mtd\" does not exist."
        exit 5
    fi

    if [ ! -c "/dev/mtd0" ]; then
        echo "NAND flash partition file \"/dev/mtd0\"does not exist."
        exit 6
    fi

    # Get partition size
    partition_size=0x`cat /proc/mtd | grep mtd0 | awk '{print $2}'`

    # The image file size needs to be greater than or equal to the partition size
    _part_size=`printf %d ${partition_size}`
    if [ ${_part_size} -gt ${image_size} ]; then
        echo "The format of the minimum boot image is incorrect."
        echo "The image file size(${image_size}) needs to be greater than or equal to the partition size(${_part_size})"
        echo "Please use the image file officially provided by Horizon Robotics."
        exit 7
    fi

    echo "Start Update Minimum Boot..."
    echo "Please do not terminate the upgrade or power off during the upgrade."

    flash_erase /dev/mtd0 0 0
    if [ $? -ne 0 ]; then
        echo "flash_erase /dev/mtd0 failed, Please retry."
        exit 8
    fi
    nandwrite --input-size=0x600000 -p -N /dev/mtd0 ${min_boot_image}
    if [ $? -ne 0 ]; then
        echo "nandwrite /dev/mtd0 failed, Please retry."
        exit 9
    fi

    flash_erase /dev/mtd1 0 0
    if [ $? -ne 0 ]; then
        echo "flash_erase /dev/mtd1 failed, Please retry."
        exit 10
    fi
    nandwrite --input-skip=0x600000 -p -N /dev/mtd1 ${min_boot_image}
    if [ $? -ne 0 ]; then
        echo "nandwrite /dev/mtd1 failed, Please retry."
        exit 11
    fi

    sync
    echo "Update Minimum Boot Done."
    echo "=============================================="
    echo "Please reboot for the upgrade to take effect."
    echo "=============================================="
    exit 0
}

main $@
