#!/bin/sh
#------------------------------------------------------------------
#
# btldr_check - Sanity check to make sure bootloader is sane.
#
# Feb 2016 Joel Aller
#
# Copyright (c) 2016 by cisco Systems, Inc.
# All rights reserved.
#------------------------------------------------------------------
#set -x

. /usr/bin/platformfunc.sh

BOOTED=`plat_get_bootloader_booted`
BOOTVER=`plat_get_bootloader_version`
BOOTIMG=`plat_get_show_bootloader_booted`
FORCEBOOT=`plat_get_bootloader_forcebooted`

if [ -z $BOOTED -o -z $BOOTVER ]; then
    echo ERROR: No bootloader info
    exit 1
fi

if [ ! -z $FORCEBOOT ] && [ $FORCEBOOT -eq 1 ]; then
    echo INFO: forceboot from $BOOTIMG, bypass bootloader check
    exit 0
fi

[ -f /firmware/btldr.img ] && BUNDLE=/firmware/btldr.img

/usr/bin/btldr_upgrade -b $BOOTED -v $BOOTVER $BUNDLE
if [ $? -ne 0 ]; then
    # Bootloader got upgraded. Let's reboot...
    echo Bootloader upgraded.  Rebooting in 5 seconds...
    sleep 5
    reboot -r "Bootloader Upgraded"
elif [ ! -z $BUNDLE ]; then
    # Bootloader up-to-date. Remove cached bundle image (if there was).
    rm -f $BUNDLE
fi
exit 0
