# linux script server tarball functions encapsulation
# Longwei Lai
###################################################################

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

# 创建启动配置
function _create_start_file() {
    log_info "create start config ${____APP_START_CONF_NAME} ..."
    local server_name=${1}
    local proj_name=${2}
    local product_opt=${3}
    local working_dir=${4}
    local cfg_file="${SVR_PATH}/${____APP_START_CONF_NAME}"

    function _append_line() {
        echo "${1}=\"${2}\"" >> ${cfg_file}
    }

    function _append_include() {
        echo "include \"${1}\"" >> ${cfg_file}
    }

    rm -rf ${cfg_file}

    _append_include "framework/snconfig"

    case ${server_name} in
        loginserver)
            _append_include "login/snconfig"
            _append_line "app_type" "ls"
        ;;
        globalserver)
            _append_include "global/snconfig"
            _append_line "app_type" "ms"
        ;;
        webserver)
            _append_include "web/snconfig"
            _append_line "app_type" "ws"
        ;;
        gameserver)
            _append_include "game/snconfig"
            _append_line "app_type" "gs"
        ;;
        ruinsserver)
            _append_include "game/snconfig"
            _append_line "app_type" "rs"
        ;;
        devilserver)
            _append_include "game/snconfig"
            _append_line "app_type" "ds"
        ;;
        pyramidserver)
            _append_include "game/snconfig"
            _append_line "app_type" "ps"
        ;;
        cloudserver)
            _append_include "game/snconfig"
            _append_line "app_type" "cp"
        ;;
        *)
            log_info "未知[应用类型]参数"
            return 1
        ;;
    esac

    case ${proj_name} in
        boe|ww)
            _append_line "app_project" ${proj_name}
        ;;
        *)
            log_info "未知[应用项目]参数"
            return 1
        ;;
    esac

    case ${product_opt} in
        product)
            _append_line "app_env" "pro"
        ;;
        internal)
            _append_line "app_env" "sit"
        ;;
        *)
            log_info "未知[应用环境]参数"
            return 1
        ;;
    esac

    \cp -rf "${cfg_file}" "${working_dir}/"
    log_info "`cat ${cfg_file}`"

    return 0
}

function _copy_skynet() {
    log_info "copy skynet ..."

    local super_dir=${1}
    local skynet_from="${FRAMEWORK_PATH}/skynet"
    local skynet_to="${super_dir}/skynet"
    mkdir -p "${skynet_to}"

    local skynet_copy_files=(service cservice lualib luaclib skynet LICENSE HISTORY.md README.md)
    for item in ${skynet_copy_files[@]}; do
        \cp -rf "${skynet_from}/${item}" "${skynet_to}/${item}"
    done
}

function _copy_3rd() {
    log_info "copy 3rd ..."

    local super_dir=${1}
    local thirdrd_from="${FRAMEWORK_PATH}/3rd"
    local thirdrd_to="${super_dir}/3rd"

    mkdir -p ${thirdrd_to}

    for item in `ls ${thirdrd_from}`; do
        local item_from=${thirdrd_from}/${item}
        local item_to=${thirdrd_to}/${item}
        if [ -d "${item_from}" ]; then
            mkdir -p ${item_to}
            
            if [ ! -z "`find "${item_from}" -type f -name '*.so'`" ]; then
                \cp -rf "${item_from}/"*.so "${item_to}/"
            fi

            if [ ! -z "`find "${item_from}" -type f -name '*.lua'`" ]; then
                \cp -rf "${item_from}/"*.lua "${item_to}/"
            fi
        else
            \cp -rf "${item_from}" "${item_to}"
        fi
    done
}

function _copy_luasrc() {
    local working_dir=${1}
    local server_name=${2}
    function _copy_dir() {
        local name=${1}
        log_info "copy ${name} lua src ..."
        \cp -rf "${SVR_PATH}/${name}" "${working_dir}/"
    }

    case ${server_name} in
        loginserver) _copy_dir "login";;
        globalserver) _copy_dir "global";;
        webserver) _copy_dir "web";;
        gameserver|ruinsserver|devilserver|pyramidserver|cloudserver) _copy_dir "game";;
        *)
            log_info "Unknown application type ${server_name}"
            exit 1
        ;;
    esac
}

function _copy_others() {
    log_info "copy others ..."

    local working_dir=${1}
    \cp -rf "${____FWK_SVR_OPTIONS_PATH}" "${working_dir}/"
    \cp -rf "${SVR_PATH}/run" "${working_dir}/run"
}

function _create_version_file() {
    log_info "creating server version file[SERVER_VERSION.txt] ..."

    local working_dir=${1}
    local isdebug_prompt=${2}
    local product_opt=${3}
    local proj_name=${4}
    local server_name=${5}
    local svr_desc_file="${working_dir}/SERVER_VERSION.txt"

    echo -e "SERVER BUILD OPTION: ${isdebug_prompt}, ${product_opt}\n" > "${svr_desc_file}"
    echo -e "--------------------------------------------------------------------------\n" >> "${svr_desc_file}"
    echo -e "PROJECT NAME: ${proj_name}" >> "${svr_desc_file}"
    echo -e "SERVER NAME:  ${server_name}" >> "${svr_desc_file}"
    echo -e "BUILD NUMBER: ${BUILD_NUMBER}" >> "${svr_desc_file}"
    echo -e "WHY BUILD: ${WHY_BUILD}" >> "${svr_desc_file}"
    echo -e "" >> "${svr_desc_file}"
    echo -e "GIT REMOTE INFO:\n`git remote -v`" >> "${svr_desc_file}"
    echo -e "GIT BRANCH:    `git branch -v | grep -e '\*\s\+' | cut -d' ' -f2-`" >> "${svr_desc_file}"
    echo -e "LAST 10 COMMITS:\n`git --no-pager log -n 10`" >> "${svr_desc_file}"
    echo -e "BUILD TIME:    `date "+%Y-%m-%d %H:%M:%S"`" >> "${svr_desc_file}"
}

function _create_md5() {
    local package_name=${1}
    local checksum_file="${package_name}.md5"
    md5sum "${package_name}" | cut -d' ' -f1 > "${checksum_file}"

    log_info "file checksum: `cat "${checksum_file}"`"
}

function _clean_tmp_files() {
    log_info "clean tmp files ..."

    local working_dir=${1}
    find "${working_dir}" -type f -name '.*.pid' -print0 |xargs -0 rm -rf # .*.pid: pid files
    find "${working_dir}" -type f -name '*.log.*' -print0 |xargs -0 rm -rf # *.log.xxxx-xx-xx: log files
    find "${working_dir}" -type f -name '*.nohup' -print0 |xargs -0 rm -rf # .*.nohup: nohup files
    find "${working_dir}" -type f -name '.*.nohup' -print0 |xargs -0 rm -rf # .*.nohup: nohup files
}

function _tarball_files() {
    log_info "tarball files ..."

    local working_dir=${1}
    local package_name=${2}

    log_info "build reason: ${WHY_BUILD}"
    log_info "tarball: ${package_name}"

    ( cd "${working_dir}" && tar -jcvf "${package_name}" ./ > /dev/null )
    if [ $? -ne 0 ]; then
        log_err " build server tarball file failed"
    else
        \rm -rf "${working_dir}"
    fi
}

function _copy_framework() {
    local working_dir=${1}
    local item_to="${working_dir}/framework"
    for item in `ls ${FRAMEWORK_PATH}`; do
        case "${item}" in
            skynet) _copy_skynet ${item_to};;
            3rd) _copy_3rd ${item_to};;
            *)
                echo "copy ${item} ..."
                \cp -rf "${FRAMEWORK_PATH}/${item}" "${item_to}/"
            ;;
        esac
    done
}

function tar_server() {
    echo tar_server $@

    local dbg_flag="`echo -n "$1" | tr [:lower:] [:upper:]`"
    local internal_flag="`echo -n "$2" | tr [:lower:] [:upper:]`"
    local pure_opt="`echo -n "$3" | tr [:upper:] [:lower:]`"
    local is_make="`echo -n "$4" | tr [:upper:] [:lower:]`"

    local dbg_opt=FALSE
    local isdebug_prompt=release
    if [ "${dbg_flag}" = "DEBUG" -o "${dbg_flag}" = "DBG" -o "${dbg_flag}" = "D" ]; then
        dbg_opt=TRUE
        isdebug_prompt=debug
    fi

    # if not specific compile environment, compile all environments packages
    if [ -z "${internal_flag}" ]; then # TODO: all environments server tarball files build will open at later
        tar_server "${dbg_flag}" product
        test $? -eq 0 || return 1
        return
    fi

    local begin_tarball_time=`date +%s`
    local product_opt="product"
    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

    local proj_name="${PROJECT_NAME}"
    if [ -z "${proj_name}" ]; then
        proj_name='ukn_proj'
    fi

    local server_name="${SERVER_NAME}"
    if [ -z "${server_name}" ]; then
        server_name='ukn_svr'
    fi

    # is need make
    if [ "${is_make}" != "nomake" ]; then
        log_info "making ..."

        make_server "${dbg_flag}" $2
        if [ $? -ne 0 ]; then
            log_err "build server failed"
            return 1
        fi
    else
        log_info "no make ..."
    fi

    local tarball_dir="${SVR_PATH}/tarballs"
    local working_dir="${tarball_dir}/onemt.server"
    local package_name="${tarball_dir}/onemt.${proj_name}.server.${server_name}.${product_opt}.${pure_opt}.tar.bz2"

    mkdir -p "${tarball_dir}"
    \rm -rf "${working_dir}"
    mkdir -p "${working_dir}"

    _copy_framework ${working_dir}
    _copy_others ${working_dir}
    _copy_luasrc ${working_dir} ${server_name}

    _create_start_file ${server_name} ${proj_name} ${product_opt} ${working_dir}
    _create_version_file ${working_dir} ${isdebug_prompt} ${product_opt} ${proj_name} ${server_name}
    _clean_tmp_files ${working_dir}
    _tarball_files ${working_dir} ${package_name}
    _create_md5 ${package_name}

    local tarball_used=$((`date +%s` - ${begin_tarball_time}))
    log_info "done! used time: ${tarball_used} seconds"
}
