# linux script logic server build(included tarball) about functions encapsulation
# Longwei Lai
###################################################################

source "${____LOGIC_SCRIPT_PATH}/lnx_fwk_defs.sh"
source "${____LOGIC_SCRIPT_PATH}/lnx_logic_defs.sh"

# return make server
function make_server()
{
    local debug_opt=FALSE
    local isdebug_prompt=release
    local make_flags="config=release"
    local debug_flag="`echo -n "$1" | tr [:lower:] [:upper:]`"
    if [ "${debug_flag}" = "DEBUG" -o "${debug_flag}" = "DBG" -o "${debug_flag}" = "D" ]; then
        debug_opt=TRUE
        isdebug_prompt=debug
        make_flags="config=debug"
    fi

    local product_opt="product"
    local premake_path="${____LOGIC_SCRIPT_PATH}/"
    local internal_flag="`echo -n "$2" | tr [:lower:] [:upper:]`"
    if [ "${internal_flag}" = "INTERNAL" -o "${internal_flag}" = "INTERNAL_ENV" -o "${internal_flag}" = "INL" ]; then
        product_opt="internal"
    elif [ "${internal_flag}" = "PRESSURE_TEST" -o "${internal_flag}" = "PRESSURE_TEST_ENV" -o "${internal_flag}" = "PT" ]; then
        product_opt="pressure_test"
    fi

    # stop all servers
    log_info "stop all servers..."
    stop_all_servers 1>/dev/null 2>&1

    # make
    log_info "making(${isdebug_prompt}, ${product_opt})..."

    local make_log_path="${SVR_PATH}/.make_logs"
    mkdir -p "${make_log_path}"

    local make_log_file="${make_log_path}/make_log.`date '+%Y%m%d_%H%M%S_%N'`"
    log_info "make log redirect to [${make_log_file}]..."
    ( cd "${SVR_PATH}" && make linux "${make_flags}" 2>&1 | tee "${make_log_file}" | grep -e '\(error\)\|\(warning\)'; exit ${PIPESTATUS[0]} )
    if [ $? -ne 0 ]; then
        log_err "make server failed"
        return 1
    fi

    # generate option file
    log_info "generate server options..."
    mkdir -p "${____FWK_SVR_OPTIONS_PATH}"
    echo -n ${debug_opt} > "${____FWK_SVR_DEBUG_OPTION_FILE}"
}

function make_project()
{
    local projname="$1"
    local make_flags="$2"
    local make_log_file="$3"
    log_info "building ${projname} project..."
    ( cd "${make_path}" && make -f "${projname}.make" "${make_flags}" 2>&1 | tee "${make_log_file}" | grep -v '): warning CS.*'; exit ${PIPESTATUS[0]} )
    if [ $? -ne 0 ]; then
        log_err "make failed(build ${projname} project failed)"
        return 1
    fi
}
