#!/bin/sh

source /ciena/scripts/utils.sh
source /ciena/scripts/saos_utils.sh

clear_boot_count()
{
    # check if the cookie, ParamType_BootBankSwap, exists before trying to clear it
    param_cmd read $ParamType_BootBankSwap &> /dev/null

    if [ $? = "0" ]; then
        TMP=$(mktemp)

        param_cmd tofile $ParamType_BootBankSwap $TMP

        BOOT=$(hexdump -n 4 -e '1/4 "%u"' $TMP)

        rm $TMP

        # The following cookie definition was grabbed from upgrade_utils/upgrade.h
        #
        # typedef union {
        #    uint32_t rawCookie;
        #    struct {
        #       uint32_t numFailedBoots : 8;
        #       uint32_t padding        : 6;
        #       uint32_t bankSwitched   : 1;
        #       uint32_t lastBootBank   : 1;
        #       uint32_t unused         : 16;
        #    } s;
        # } BootBankSwapCookie;

        # Don't write the cookie if numFailedBoots is already zero.
        [ $(( $BOOT & 0xFF000000 )) == "0" ] && return

        # Clear numFailedBoots (see BootBankSwapCookie in upgrade.h), the boot limit counter.
        param_cmd write $ParamType_BootBankSwap $(( $BOOT & 0xFFFFFF ))
    fi
}

boot_chain_ack()
{
    local bank=$1

    # The following header definition was grabbed from upgrade_utils/upgrade.h
    #
    # typedef struct {
    #     uint32_t   ihMagic;
    #     uint32_t   ihLength;
    #     uint32_t   ihVersion[2];
    #     uint32_t   ihBuildTime;
    #     uint32_t   ihCompressedFlag;
    #     uint32_t   ihSize;
    #     uint32_t   ihCRC32;
    #     uint32_t   ihBootFlags;
    #     uint32_t   __reserved__[23+32];
    # } ImageHeader;

    BOOTFLAGS_OFFSET=32
    MAGIC=$(( 0xbabeface ))
    IMAGE=/dev/mtd/u-boot-$bank

    # Make sure we are dealing with a valid header before writing to it.
    [ $(hexdump -n 4 -e '1/4 "%u"' $IMAGE) == $MAGIC ] || return

    FLAGS=$(dd if=$IMAGE skip=$BOOTFLAGS_OFFSET bs=1 count=4 2> /dev/null | hexdump -n 4 -e '1/4 "%u"')

    # If ihBootflags is already == BOOT_FLAGS_VALID_IMAGE_BIT then avoid writing
    # to prevent excessive wear on the flash.
    [ $FLAGS == "1" ] && return

    # Need to clear all but the BOOT_FLAGS_VALID_IMAGE_BIT bit (bit 0) in
    # ihBootFlags of the image header. Since bits in this field are only
    # cleared we don't need to erase flash here.
    echo -en '\x00\x00\x00\x01' | dd of=$IMAGE seek=$BOOTFLAGS_OFFSET obs=1 conv=notrunc 2> /dev/null
}

if spiboot_supported; then
    spiboot_ack
else
    get_running_bank
    case $? in
        $EXIT_BANKA) bank="a" ;;
        $EXIT_BANKB) bank="b" ;;
        $EXIT_NFS)   echo "$0: Not supported with NFS boot."; exit 1 ;;
        *)           echo "$0: Unknown bank detected; Aborted."; exit 1 ;;
    esac

    clear_boot_count
    boot_chain_ack $bank
fi
