#!/bin/sh

. ../common/ajax_common


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
            if [ "`uname`" = "Linux" ]; then
                is_ipv6=`echo "${CGI_ip}" | grep ":"`
                echo "${is_ipv6}" >/root/cmd.log
                if [ "${is_ipv6}" != "" ] ; then
                    errmsg=`ping6 -c 1 ${CGI_ip} | grep -v PING | grep bytes`
                else
                    errmsg=`ping -c 1 -W 1 ${CGI_ip} | grep -v PING | grep bytes`
                fi
            else
                errmsg=`ping -o -t 1 ${CGI_ip} | grep -v PING | grep bytes`
            fi
            timer=`echo ${errmsg} | grep icmp | cut -d" " -f7 | awk -F "=" '{t=sprintf("%.2f", $2);print t}'`
            ttl=`echo ${errmsg} | grep icmp | cut -d" " -f6 | cut -d"=" -f2`
        else
            print_json_head
            ${TCPPING} ${CGI_ip} ${CGI_port}
            exit 0
        fi
    else
        is_ipaddr ${CGI_ip}
        [ $? = "1" ] && CGI_ip=`nslookup_url ${CGI_ip}`
        CGI_id=`echo ${CGI_id} | cut -d"-" -f2`
        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`
    fi

    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}}"
    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
