#!/bin/bash

if [ $# == 1 ]; then
    echo "---------------------------------------------------------------"
    echo " Set scrypto tool path using global env variable"
    if [ -n $TZ_SCRYPTO_TOOLS_PATH ]; then
        TZ_SCRYPTO_TOOLS_PATH="$( cd "$( dirname "$0" )" && pwd -P )"
        echo " Global env variable is not set, set to default path : $TZ_SCRYPTO_TOOLS_PATH"
    fi
    echo "---------------------------------------------------------------"
elif [ $# == 2 ]; then
    echo "---------------------------------------------------------------"
    echo " Set scrypto tool path using user input"
    echo "---------------------------------------------------------------"
    TZ_SCRYPTO_TOOLS_PATH=$2
else
    echo "---------------------------------------------------------------"
    echo " [Warning] Use below format"
    echo "    "
    echo "./run_fips_tools.sh <input elf file>"
    echo " or"
    echo "./run_fips_tools.sh <input elf file> <scrypto tools path>"
    echo "---------------------------------------------------------------"
    exit 1
fi

source ${TZ_SCRYPTO_TOOLS_PATH}/utils.sh
TZ_SCRYPTO_TOOLS_IMPRINT=${TZ_SCRYPTO_TOOLS_PATH}/imprint256

if [ ! -e "$TZ_SCRYPTO_TOOLS_IMPRINT" ]; then
    print_error "imprint256 is not found: IMPRINT = $TZ_SCRYPTO_TOOLS_IMPRINT"
fi

function imprint()
{
    print_info "$ELF_FILE"
    $TZ_SCRYPTO_TOOLS_IMPRINT "$ELF_FILE" || print_error "fips signature embedding failed"
}

ELF_FILE=$1

if [ -e "$CHECK_FIPS_SYM" ]; then
    # developer build embeds fips signature (HMAC)
    # and stores FIPS covered len into ${IN_OUT_FILE}
    ELF_FIPS_COVERED_LEN=0
    export IN_OUT_FILE=$(mktemp)
    imprint
    if [ -f "${IN_OUT_FILE}" ]; then
        # get FIPS covered area len to pass it into syms checking
        ELF_FIPS_COVERED_LEN=$(cat "${IN_OUT_FILE}")
        rm -f "${IN_OUT_FILE}"
        $CHECK_FIPS_SYM "$ELF_FILE" "$REFERENCE_LIST" "$ELF_FIPS_COVERED_LEN" || exit 1
    else
        print_error "tool process internal error"
    fi
else
    # client build embeds fips signature (HMAC) only
    imprint
fi

exit 0
