#!/bin/sh

# This script is invoked from FTP or WBI when a user provides an unbundled EC firmware file. (put filename.bin encl:...)
# Expectations:
# - filename is in the format "encl:<bus>:<target>[,<bus>:<target>,...]"
# - firmware file is located in /mnt/ramdisk
# - there is only one encl firmware file available at one time
# - WBI uses flag target encl:999:999 to indicate the presence of another file containing the EC list (/mnt/ramdisk/listOfEnclosures)

source /usr/bin/utils.sh

actComp="/ec"

fileFormat="/mnt/ramdisk/encl*"
numFiles=$(ls $fileFormat | wc -l)

if [ $numFiles -eq 0 ]
then
    apiError $actComp 1056 "EMP firmware file was not found."
    echo "EMP firmware file was not found."
    echo "RETURN_CODE: 11"
    exit 11
elif [ $numFiles -gt 1 ]
then
    apiError $actComp 1055 "Multiple EMP firmware files were found. Unable to proceed."
    echo "Multiple EMP firmware files were found. Unable to proceed."
    echo "RETURN_CODE: 11"
    exit 11
fi

# there is exactly one disk firmware file
filename=$(basename $fileFormat)

if [ ! -r $filename ]
then
    apiError $actComp 1055 "EMP firmware file is unreadable for target $filename."
    echo "EMP firmware file is unreadable for target $filename."
    echo "RETURN_CODE: 11"
    exit 11
fi

# Pull the address out of the filename, which should be of the form encl[:<list of encl.slot pairs>]
# Note that if the user didn't specify an address, $addr will be set to "encl"
addr=$(echo $filename | sed "s/encl://")

if [[ $addr == encl* ]] # "encl" without target list not supported
then
    apiError $actComp 1105 "Invalid FTP target: $addr."
    echo "Invalid FTP target: $addr. Expected usage: put <filename> encl:<bus>:<target>[,<bus>:<target>,...]"
    echo "RETURN_CODE: 11"
    exit 11
else # Target was entered in format encl:<addr>
    if [ "$addr" == "999:999" ] # WBI flag value
    then
        # WBI pushes a potentially long list of EMPs into a txt file
        listFile="/mnt/ramdisk/listOfEnclosures"
        if [ ! -r $listFile ]
        then
            apiError $actComp 1055 "EMP list from WBI was unreadable."
            echo "EMP list from WBI was unreadable."
            echo "RETURN_CODE: 11"
            exit 11
        fi

        addr=$(head -1 $listFile)

        if [ -z "$addr" ];
        then
            apiError $actComp 1105 "EMP list from WBI was empty."
            echo "EMP list from WBI was empty."
            echo "RETURN_CODE: 11"
            exit 11
        fi
    fi

    apiActive $actComp "Updating selected EMP(s) with the provided firmware file."
    echo "Updating selected EMP(s) with the provided firmware file."

    /usr/bin/capi.app --loadec $filename --list $addr --component $actComp -x
fi

if [ $? -ne 0 ]
then
    echo "*** Code Load Fail. Failed to successfully update expansion-module firmware. ***"
    echo "RETURN_CODE: 11"
    exit 11
fi

echo "RETURN_CODE: 9"
exit 0

