#!/usr/bin/env bash
# huangyongxing@yeah.net
# 模拟客户端编译运行管理

BASE_DIR=$(cd $(dirname $0); pwd)

cd ${BASE_DIR}/
APP_PATH=$(pwd)/config

SVR_PATH=$(dirname $(dirname ${BASE_DIR}))
BEAM_PATH=${SVR_PATH}/ebin

ERL_OPTION_NO_SMP="+P 204800 +K true +A 100 +spp true -smp disable -hidden +sbwt none"
ERL_OPTION_SMP="+P 204800 +K true +A 100 +spp true -smp enable -hidden +sbwt none"

# ERL=/opt/erlang-otp-19.3/bin/erl
# ERL=/opt/erlang-otp-23.2.6/bin/erl
ERL=erl

function fun_start() {
    # 切换到BEAM_PATH，以确保logs目录的相对位置正确
    cd ${BEAM_PATH}
    local nodeName=imitation$RANDOM@127.0.0.1
    local cookie=test
    "${ERL}" ${ERL_OPTION_SMP} -name ${nodeName} -setcookie ${cookie} -boot start_sasl -sasl sasl_error_logger false -sasl errlog_type error -pa ${APP_PATH} -pa ${SVR_PATH}/config -s cli_simu start
}

function fun_make() {
    cd ${SVR_PATH}
    # "${ERL}" -noinput -smp enable -make

    # local makeOptions='[{i,"include"},{outdir,"ebin"}]'
    # "${ERL}" -noinput -smp enable -eval "Files = filelib:wildcard(\"test/cli_simu/src/*.erl\"), make:files(Files, ${makeOptions})" -s c q

    "${ERL}" -noinput -smp enable -eval "Files = filelib:wildcard(\"test/cli_simu/src/**/*.erl\"), make:files(Files)" -s c q
}

function usage() {
    cat <<EOF
--------------------------------------------------------------------------
    m 编译
    s 开启模拟客户端管理器
    q 退出
    (10分钟未输入指令将自动退出)
--------------------------------------------------------------------------
EOF
}

function main() {
    local input
    usage
    while read -t 600 input
    do
        cd ${APP_PATH}
        case "$input" in
            "m")
                fun_make
                ;;
            "s")
                fun_start
                ;;
            "q")
                break;;
            *)
                continue;;
        esac
        usage
    done
}

main
