# linux script server http interactive logic functions encapsulation.
# Longwei Lai
###################################################################

source "${____FWK_SCRIPT_PATH}/lnx_fwk_path.sh"
source "${____FWK_SCRIPT_PATH}/lnx_fwk_server.sh"
source "${____LOGIC_SCRIPT_PATH}/lnx_logic_defs.sh"
source "${____LOGIC_SCRIPT_PATH}/lnx_logic_serversql.sh"

# send http message to specific node
# arguments:
#   arg1: node
#   arg2: message cmd(integer)
#   arg3: sub message cmd(integer)
#   arg4: http message(what message do you want to send?)
# returns:
#   echo style:
#       server return message
#   return style:
#       0: success
#       <other>: failed
function send_httpmsg_to_node()
{
    local node="$1"

    local msg_cmd="$2"
    local msg_subcmd="$3"
    local http_msg="$4"

    local verify_key="${____SERVER_HTTP_KEY}"
    local now_time=`date "+%s"`

    # calculate sign
    local verify_sign="`echo -n "${now_time}${verify_key}" |  md5sum | cut -d ' ' -f 1`"

    # get http access info
    local http_info=(`exec_sql_cmd_on_confdb "SELECT web, port FROM conf_http WHERE nodeid = ${node}"`)
    if [ $? -ne 0 ]; then
        log_err "failed to get http access port from mysql!"
        log_err "failed to send http message[${http_msg}] to node: ${node}!"
        return 1
    fi
    local http_addr="http://${http_info[0]}:${http_info[1]}"

    local http_packet="{\"cmd\":${msg_cmd}, \"subcmd\": ${msg_subcmd}, \"data\": ${http_msg}, \"sign\": \"${verify_sign}\", \"time\":${now_time}}"
    local curl_ret="`curl --max-time 8 -s -d "${http_packet}" "${http_addr}"`"
    local curl_ret_code=$?
    if [ ${curl_ret_code} -ne 0 ]; then
        echo -n "${curl_ret}"
        return ${curl_ret_code}
    else
        echo -n "${curl_ret}"
        return 0
    fi
}

