#!/bin/bash

source ${TOOLS_DIR}/utils.sh

APPLIB_FILE="$1"

case ${MACHINE} in
    32)
        OBJCOPY="$SWD_TOOLCHAIN_LINARO_PATH/bin/arm-linux-gnueabihf-objcopy"
    ;;
    64)
        OBJCOPY="$SWD_TOOLCHAIN_LINARO_AARCH64_PATH/bin/aarch64-none-elf-objcopy"
    ;;
    *)
        print_error "Unsupported MACHINE type: $MACHINE"
    ;;
esac

if [ "$APPLIB_FILE" == "" ];
then
    print_error "No argument. Specify library file to patch." >&2
fi

if [ ! -f ${APPLIB_FILE} ];
then
    print_error "${RED}[ERROR]${NC}" "No such file: ${APPLIB_FILE}." >&2
fi

# Need for applib32, applib64 in SDM660 nhlos
# Remove, when Qualcomm will fix OPENSSL and BN* symbols issue
print_warning "Build Trustlet for SDM660 require patch applib step, due to conflict in OPENSSL and BIGNUM symbols"
print_warning "This step may not be mandatory in next revisions of nhlos."

IS_T_OPENSSL=$(nm ${APPLIB_FILE} | grep "T OPENSSL*")
IS_T_BIGNUM=$(nm ${APPLIB_FILE} | grep "T BN*")

if [ "$IS_T_OPENSSL" == "" ] && [ "$IS_T_BIGNUM" == "" ]
then
    print_success "No need to patch."
else
    print_warning "Patching... "

    ${OBJCOPY} -w -W BN_* ${APPLIB_FILE}
    ${OBJCOPY} -w -W bn_* ${APPLIB_FILE}
    ${OBJCOPY} -w -W OPENSSL_* ${APPLIB_FILE}
fi

exit 0
