# ---------- kernel update ----------
KERNEL_MD5=""

flash_kernel()
{
    _KERNEL_PARTITION=$1

    logmsg "I" "fl_kl1" "partition=${_KERNEL_PARTITION}" "flashing kernel"

    BLOCK_SIZE=131072
    local _BLOCK_COUNT=$(( $( stat -c %s uImage ) / ${BLOCK_SIZE} ))

    flash_unlock /dev/mtd/${_KERNEL_PARTITION}

    _RET=1

    _FL_RETRY_PAUSE=2

    _FL_COUNT=0
    _FL_RETRIES=3

    while [ ${_FL_COUNT} -lt ${_FL_RETRIES} ]; do
        echo "flashing via \"dd if=uImage of=/dev/mtdblock/${_KERNEL_PARTITION}\""

        dd if=uImage of=/dev/mtdblock/${_KERNEL_PARTITION} bs=${BLOCK_SIZE}
        _RES=$?

        sleep 1
        sync

        echo "flash status ${_RES}"

        if [ ${_RES} -eq 0 ]; then

            _RET=0

            _FL_COUNT=${_FL_RETRIES}

        else
            sleep ${_FL_RETRY_PAUSE}

        fi

        _FL_COUNT=`expr ${_FL_COUNT} + 1`

    done

#    update_percent_complete 1

    logmsg "I" "fl_kl3" "status=${_RET}" "kernel update complete"

    return ${_RET}
}


perform_kernel_update()
{
	KERNEL=$1
    tar xzvf ${KERNEL} && rm -f ${KERNEL}

    logmsg "I" "fl_kl" "verifying kernel image"

    _CHECK_MD5=`md5sum uImage | awk '{ print $1 }'`
    if ! [ "${KERNEL_MD5}" = "${_CHECK_MD5}" ]; then
        logmsg "C" "fl_kl0" "source_md5=${KERNEL_MD5},bundle_md5=${_CHECK_MD5}" "kernel checksum failure"

        return 1
    fi

    . ./uImage.partitions

    flash_kernel ${KERNEL_PARTITION_1}
    _RET=$?

    if [ ${_RET} -ne 0 ]; then
        return ${_RET}
    fi

    update_progressbar 50

    local _MTD_2_SIZE=`awk '/Kernel2/ { print $2 }' /proc/mtd`
    if [ -n "${_MTD_2_SIZE}" ]; then
        if ! [ "${_MTD_2_SIZE}" = "00000000" ]; then
            flash_kernel ${KERNEL_PARTITION_2}
            _RET=$?
        fi
    fi

    update_progressbar 100

    # This just allows time for the progress bar to draw 100%
    sleep 1

    rm -f ./uImage*

    return ${_RET}
}

