#!/bin/sh

# NOTE: our output is going to /mnt/ramdisk/codeload.progress

export BD="/mnt/ramdisk"
export CFG="/mnt/cfg"

# gives us raw API message capability
source /usr/bin/utils.sh

# use the one we brought with us
source ${BD}/mc/fcns.shinc

actComp="/"

SUCCESS=255

# pfud had this going when we got transferred over, so get rid of it so that codeload.progress gets monitored.
rm ${BD}/pfu.progress 2>/dev/null

# Tried to move call to killnonessential out of ftpd.c and call it
# later in this script.  That would allow us to avoid a reboot until
# the bundle was validated to be somewhat reasonable.   Unfortunately,
# that was a no-go.  It had some side-effects that I ran out of
# time tracking down.  So, if this script is called, you're gonna reboot.
DO_REBOOT=false
DO_REBOOT_SC=false

# The progressmonitor is workaround for ftp client timeouts.
# It outputs a message every so often if nothing has been added
# to the codeload.progress file (which means also output to client).
# It is killed in cleanup().
progressmonitor /mnt/ramdisk/codeload.progress &
PMPID=$!


# =====================================================================
# No matter what, run this function on exit
# =====================================================================
exitTrapFcn()
{
    local SUCCESS=$?

    if [ "$SUCCESS" -ne "0" ]
    then
        # CAUTION: Some script writers (specifically, at Sepaton) are keying off
        # the phrase "Code Load Fail.", so don't change this wording.  Also, don't
        # change the phrase "Code load completed successfully." in this file for the same reason.
        # Note: Plain echo is for FTP output; redirected echo is for WBI output.
        echo "*** Code Load Fail. ***"
        echo "STATUS: *** Code Load Fail. ***"
        if $DO_REBOOT; then
            echo "Restarting Management Controller..."
            echo "RETURN_CODE: 10"
        else
            echo "RETURN_CODE: 11"
        fi
        apiError $actComp 1000 "Code load failed."
    else
        echo "Code load completed successfully."
        echo "STATUS: Code load completed successfully."
        if $DO_REBOOT; then # some kind of reboot will take place
            if $DO_REBOOT_SC; then # both the SC and MC
                finishScCodeload
                echo "Restarting Storage Controller and Management Controller. This will take a couple of minutes."
            else # only MC
                echo "Restarting Management Controller..."
            fi
            echo "RETURN_CODE: 8"
        else # no reboot
            echo "RETURN_CODE: 9"
        fi
        apiOK $actComp
    fi

    if [ -f  /mnt/ramdisk/codeload.progress ]
    then
       cp /mnt/ramdisk/codeload.progress /cfg/last.codeload.progress
    fi

    if $DO_REBOOT; then
        # Delay so messaging can get out to WBI.
        disconnectFTP
        if $DO_REBOOT_SC; then
            # we're going to hit the board, so we need to ensure the SC is shutdown
            /usr/bin/capi.app --prepare -x
            safeRebootSc
        else # MC only
            /usr/bin/reboot.sh 30
        fi
        cleanup
    else # No reboot - pause while cleaning up
        cleanup pause
    fi

    return $SUCCESS
}
trap exitTrapFcn SIGINT SIGTERM EXIT

cleanupViaMd5()
{
    local filename
    local folder
    local md5file=allfiles.md5

    # delete all files and folders referenced in the md5sum file

    oldIFS=$IFS
    IFS=$'\n'
    for line in $(cat $md5file); do
        filename=${line#*\./}
        rm -f $filename

        # folders have at least one slash
        case "$filename" in
          */*)
            folder=${filename%%/*}
            rm -rf $folder/
            ;;
        esac

    done
    IFS=$oldIFS

    rm -f $md5file
}

cleanup ()
{
    # need to pause for a few seconds to get last echo text
    [ "$1" == "pause" ] && sleep 4

    logger "Cleaning up from dosecondaryload"

    [ -f allfiles.md5 ] && cleanupViaMd5

    # Clean up any files that are left lying around.
    rm bundle.bin 2>/dev/null
    rm -f bundleinfo 2>/dev/null
    rm -f capi.app 2>/dev/null
    rm -f clixml.sh 2>/dev/null
    rm -f comparelevel.awk 2>/dev/null
    rm -f contents.xml 2>/dev/null
    rm update.sh 2>/dev/null
    rm -f utils.sh 2>/dev/null
    rm image.fla 2>/dev/null
    rm -f do.* 2>/dev/null
    rm -f showsystem.cmd 2>/dev/null
    rm -f pokesc.bin 2>/dev/null
    rm -f returnlevel.awk 2>/dev/null
    rm -f is.* 2>/dev/null
    rm fifo 2>/dev/null
    rm encl* 2>/dev/null
    rm disk* 2>/dev/null
    rm listOf* 2>/dev/null
    rm -rf bundle 2>/dev/null
    rm -rf cpld 2>/dev/null
    rm -rf mc 2>/dev/null
    rm -rf sc 2>/dev/null
    rm -rf ec 2>/dev/null
    rm -rf system 2>/dev/null
    rm -rf bin 2>/dev/null
    kill -9 $PMPID
}

date
cd /mnt/ramdisk

# here we roll progress
rollProgress

# check to see if getlogs or managedlogs is occurring before we start - getlogs.progress is the first thing those operations touch
if [ -f getlogs.progress ]
then
    echo "*** Code Load Fail. Managed logs or get logs operation in progress. Aborting codeload operation. ***"
    apiError $actComp 1003 "Codeload and getlogs attempted simultaneously."
    cp /mnt/ramdisk/codeload.progress /cfg/last.codeload.progress
    cleanup pause
    exit 11
fi

echo "Loading bundle"
apiActive $actComp "Loading bundle."
./update.sh
if [ -f do.reboot ]; then
    DO_REBOOT=true
else
    DO_REBOOT=false
fi
exit $?

