#!/bin/sh

. ../common/ajax_common


PING="/usr/ramdisk/bin/ping"
TCPPING="/usr/ramdisk/bin/tcpping"


load_interface()
{
    . ../common/ajax_object_lib

    printf "{"
    printf "\"lan\":`lib_proxy_list lan`"
    printf ",\"wan\":`lib_proxy_list wan`"
    printf "}"
}


send_ping_packet()
{
    if [ "${CGI_id}" = "0" ]; then
        if [ "${CGI_type}" = "icmp" ]; then
            print_json_head
            ${PING} ${CGI_ip} -j
            exit 0
        else
            print_json_head
            ${TCPPING} ${CGI_ip} ${CGI_port}
            exit 0
        fi
    else
        is_ipaddr ${CGI_ip}
        if [ $? = "1" ]; then
            ${FLOWEYE} minidns add name=${CGI_ip} proxy=${CGI_id}
            sleep 1
            CGI_ip=`${FLOWEYE} minidns add name=${CGI_ip} proxy=${CGI_id} | cut -d"=" -f2`
        fi
        cmdargs="if=${CGI_id} ip=${CGI_ip}"
        if [ "${CGI_nexthop}" != "" ]; then
            cmdargs="${cmdargs} nexthop=${CGI_nexthop}"
        fi
        errmsg=`${FLOWEYE} ping ${cmdargs} count=1`
        timer=`echo ${errmsg} | cut -d" " -f6 | cut -d"=" -f2 | sed 's/ms//g' | awk '{t=sprintf("%.2f", $1);print t}'`
        ttl=`echo ${errmsg} | cut -d" " -f5 | cut -d"=" -f2`

        if [ "${errmsg}" = "" ]; then
            retjson 2 "NO Reply from ${CGI_ip}"
        elif [  "${timer}" = "0.00" -o "${timer}" = "" ]; then
            retjson 2 "${errmsg}"
        else
            retjson 0 "OK" "{\"timer\":${timer}, \"ttl\":${ttl}, \"ip\":\"${CGI_ip}\"}"
        fi
    fi
}


send_tracert_packet()
{
    tracemsg=`${FLOWEYE} tracert proxy=${CGI_proxy} dst=${CGI_dst} hop=${CGI_hop}`
    
    if [ $? -ne 0 ]; then
        retjson 1 "Fail:${errmsg}"
    else
        next_ip=`echo ${tracemsg} | cut -d" " -f3`
        location=`${FLOWEYE} ipdb get ip=${next_ip}`
        if [ $? == 0 ]; then
            location_res=`echo ${location} | cut -d" " -f1  | cut -d"=" -f2`
            tracemsg="${tracemsg} ${location_res}"
        fi
        retjson 0 "OK" "\"${tracemsg}\""
    fi
}


case "${CGI_action}" in
    "load_interface")
        retjson 0 "OK" "`load_interface`"
        ;;

    "send_ping_packet")
        action_check
        send_ping_packet
        ;;

    "send_tracert_packet")
        action_check
        send_tracert_packet
        ;;

    *)
        retjson 1 "UNKNOW_ACTION"
        ;;

esac
