# linux script logic server update about functions encapsulation
# Longwei Lai
###################################################################

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

# get version info(from git)
function get_server_version_info()
{
    log_info "Local Branch:        `git branch -v | grep -e '\*\s\+' | cut -d ' ' -f 2`"
    log_info "Remote Branch:       `git remote`/`git branch -v | grep -e '\*\s\+' | cut -d ' ' -f 2`"
    log_info "Last Commit Info:"
    log_info "`git log -1 $(get_now_git_version_no)`"
}

# update server(from git)
function update_server()
{
    local git_path="${SVR_PATH}"
    log_info "now branch:$(get_now_branch)"
    log_info "pull all updates from remote..."
    ( cd ${git_path} && git pull origin )
    if [ $? -ne 0 ]; then
        log_err "update server from git failed"
        return 1
    fi

    log_info "update all submodules..."
    ( cd ${git_path} && git submodule update --init --recursive )
    if [ $? -ne 0 ]; then
        log_err "update server submodules failed"
        return 1
    fi

    log_info "update success, update to: $(get_now_git_version_no)"
}

# switch branch
function switch_branch()
{
    local new_branch="$1"
    local old_branch="$(get_now_branch)"
    if [ "${new_branch}" = "${old_branch}" ]; then
        log_warn "same branch[${new_branch}], don't need switch"
        return 0
    fi

    git checkout -b "${new_branch}" "origin/${new_branch}"
    local co_ret=$?
    if [ ${co_ret} -ne 0 ]; then
        log_err "switch [${old_branch}] --> [${new_branch}] failed, checkout failed, return: ${co_ret}"
        return 1
    fi

    git submodule update --init --recursive
    local submodule_up_ret=$?
    if [ ${submodule_up_ret} -ne 0 ]; then
        log_err "switch [${old_branch}] --> [${new_branch}] failed, submodule update failed, return: ${co_ret}"
        return 1
    fi

    log_info "switch [${old_branch}] --> [${new_branch}] success!"
}

# get current branch
function get_now_branch()
{
    echo -n "`git branch | grep -e '\*\s\+' | cut -d ' ' -f 2-`"
}

# get current now git version no
function get_now_git_version_no()
{
    echo -n "`git branch -v | grep -e '\*\s\+' | cut -d ' ' -f3`"
}

