#!/bin/bash
set -e

LOCAL_DIR=$(dirname $(readlink -f $BASH_SOURCE))
cd ${LOCAL_DIR}

source ${LOCAL_DIR}/utils.sh

[ $TOOLS_DIR ]    || export TOOLS_DIR=$PWD && true
[ ${CONFIG_DIR} ] && source ${CONFIG_DIR}/build_configurator.sh || true

# Options Configurations ##############################################################################################

LIB_NAME="scrypto"

SHORT_OPT="h"
LONG_OPT="help,tee:,chipset:,version:,machine:,mode:,w-dir:,driver,config-dir:"

function print_help()
{
    echo "Usage: $0 [-t] TEE"
    echo "Mandatory parameters:"
    echo "  --tee                   TEE type. Values: [${TEE_ALIASES[@]}]."
    echo "  --chipset               Set explicitly chipset value. Available: [${AVAILABLE_CHIPSETS[@]}]"
    echo "  --version               Version of the library (e.g 2.1)"
    echo "  --machine               Bits of machine, 32 or 64 can be selected. Default is 32."
    echo "  --w-dir                 Working dir - means exported scrypto directory."
    echo "  --mode                  Library mode"
    echo ""
    echo "Optional parameters:"
    echo "  --config-dir    Set path to build_configurator.sh"
}

# Read the options ####################################################################################################

TEMP=`getopt -o ${SHORT_OPT} --long ${LONG_OPT} -n "$0" -- "$@"`

if [ $? != 0 ]
then
    print_error "Getopt experienced an error. Read help first (-h or --help)"
    exit 1
fi

eval set -- "${TEMP}"

# Extract options and their arguments into variables ##################################################################

while true ; do
    case "$1" in
        --tee)
            TEE=$2
            shift 2
            ;;
        --chipset)
            CHIPSET=$2
            shift 2
            ;;
        --version)
            VERSION=$2
            shift 2
            ;;
        --machine)
            MACHINE=$2
            shift 2
            ;;
        --mode)
            MODE=$2
            shift 2
            ;;
        --w-dir)
            W_DIR=$2
            shift 2
            ;;
        --config-dir)
            CONFIG_DIR=$2
            if [ ! -d "${CONFIG_DIR}" ]; then
                print_error "Error in parameter: --config-dir! Dir: \"$CONFIG_DIR\" doesn't exit!"
            fi
            source ${CONFIG_DIR}/build_configurator.sh
            shift 2
            ;;
        -h|--help)
            print_help;
            exit 0
            ;;
        --)
            shift
            break
            ;;
        *)
            print_error "Internal error! Unknown option: $1"
            exit 1
            ;;
    esac
done

# Script logic ########################################################################################################

check_required "TEE is not set. Use -h or --help for info." ${TEE}
check_required "MODE is not set. Use -h or --help for info." ${MODE}
check_required "CHIPSET is not set. Use -h or --help for info." ${CHIPSET}
check_required "MACHINE is not set. Use -h or --help for info." ${MACHINE}

check_existing "Output directory" "${W_DIR}"
check_existing "Directory with prebuilded libs" "${W_DIR}/libs"

set_name_for_tz_entity

LIBRARY_CL=""
get_current_cl_number LIBRARY_CL

TARGET=""
ALT_TARGET=""
prepare_library_name "${VERSION}" "${LIBRARY_CL}" TARGET ALT_TARGET

if [ ! -e "${W_DIR}/libs/${TARGET}" ]
then
    LIST_ALT_TARGETS=$(find ${W_DIR}/libs -type f -regex ${ALT_TARGET})
    COUNT_ALT_TARGETS="0"

    if [ -n "${LIST_ALT_TARGETS}" ]; then
        COUNT_ALT_TARGETS="$(echo "${LIST_ALT_TARGETS}" | wc -l)"
    fi

    if [ "${COUNT_ALT_TARGETS}" -ne "1" ]; then
        print_error "Only one alternative file is required"
    fi

    ALT_TARGET=$(basename "${LIST_ALT_TARGETS}")

    print_warning "Requested target ${TARGET} is not present, using alternative: \n $ALT_TARGET "
    check_existing "Alternative target library ${W_DIR}/libs/${ALT_TARGET}" "${W_DIR}/libs/${ALT_TARGET}"
    TARGET=${ALT_TARGET}
fi

print_info "TARGET: ${TARGET}"

cd ${W_DIR}

rm -f lib${LIB_NAME}.a
ln -sf libs/${TARGET} lib${LIB_NAME}.a

check_return_code $? "Making link to target library."

cd -

LINK_POINTS_TO=$(readlink -f ${W_DIR}/lib${LIB_NAME}.a)
check_existing "Link is broken. Check location: \n$LINK_POINTS_TO" "$LINK_POINTS_TO"

exit 0
