set -e

usage() {
    echo "usage: $0 [variants] [--evmy] [--cache] [--jesd] [--test caseid] " 1>&2
    msg=${1:-}
    if [ ! -z "${msg}" ]; then
        echo "error:$1"
    fi
    exit 1
}

variants=
fronthaul_option="cpri"
cache_option="no"
test_option="no"
case_id=0
board_option="EVB"

while [[ "$#" > 0 ]]; do
    case $1 in
        --cache) cache_option="yes"; shift;;   

        --evmy) board_option="EVMY"; shift;; 
        --evb) board_option="EVB"; shift;; 
        --evmyf) board_option="EVMYF"; shift;; 
        --evmyt) board_option="EVMYT"; shift;; 

        --cpri) fronthaul_option="cpri"; shift;;  
        --jesd) fronthaul_option="jesd"; shift;;   

        --test) test_option="yes";             
            if [[ ! -z "$2" ]] && [[ -n "$(echo $2 | sed -n " /^[0-9]\+$/p")" ]]; then 
                case_id=$2; shift;
            fi
            shift;;                   
                  
        --*| -*) usage "unknown option $1"; exit 1;;
        *) variants+=" $1"; shift;;
    esac;
done
       
export DIR_ROOT=$(cd `dirname "$0"`;pwd)
#echo "# script_dir:${DIR_ROOT}"
export BUILD_DIR=${DIR_ROOT}/build
if [ -d ${BUILD_DIR} ]; then
    rm -rf ${BUILD_DIR} 
fi

mkdir -p ${BUILD_DIR}  
if [[ "${fronthaul_option}" == "jesd" ]]; then
    export RFIC_DIR=${DIR_ROOT}/driver/rfic/adrv9026
    export CJSON_DIR=${DIR_ROOT}/driver/rfic/ucp/cJSON
    export RFIC_APP_DIR=${DIR_ROOT}/rfic
    export BOARD_TYPE=${board_option}

    echo -e "\n"
    echo "###### start building libjesd.a and librfic.a ######"    
    cd ${DIR_ROOT}/driver/rfic    
    chmod +x build.sh
    source ./build.sh
    cp ${RFIC_DIR}/out/jesd/*.a ${BUILD_DIR} 
    cp ${RFIC_DIR}/out/jesd/*.h ${DIR_ROOT}/interface  

    cp ${RFIC_DIR}/out/rfic/*.a ${DIR_ROOT}/lib
    cp ${RFIC_DIR}/out/rfic/ucp_api_rfic.h ${RFIC_APP_DIR}/inc/       
    cp ${CJSON_DIR}/xzJSON.h ${RFIC_APP_DIR}/inc/

    echo -e "\n"
    echo "###### start building rfic.out ######"
    cd ${RFIC_APP_DIR}/    
    make
fi

echo -e "\n"
echo "###### start building msgTransfer.out and libmsgTransfer.a ######"
cd ${DIR_ROOT}/
make cache_option=${cache_option} fronthaul_option=${fronthaul_option} test_option=${test_option} test_id=${case_id}
 
cd ${DIR_ROOT}/lib
rm -rf *.*
