#!/bin/bash

function param_ping()
{
    #特殊参数名后面的值为4或者6时，其意为ping版本
    result=`echo $1 | grep "^-.*[a|A|b|B|d|D|f|h|L|n|O|q|r|R|U|v|V][4|6]" | wc -l`
    if [ $result -ne 0 ];then
        echo $result
        return 0
    fi
    #参数名4或者6开始时，其意为ping版本
    result=`echo $1 | grep "^-[4|6]" | wc -l`
    if [ $result -ne 0 ];then
        echo $result
        return 0
    fi
    echo "0"
    return 1
}


function karbor_ping()
{
    if [[ "$(basename $0)" == "ping6" ]];then
        #使用ping6直接ping时，参数直接增加-6版本
        ping6 $@
        return $?
    fi
    declare -a argv
    len=0
    for value in $@;
    do
        if [ `param_ping $value` -ne 0 ];then
            #参数明确指明ping版本时，参数不根据ip变化
            ping $@
            return $?
        fi
        argv[$len]=$value
        let len=len+1
    done
    check_ping_6=1
    for ((index=0; index<$len; index++))
    do
        value=${argv[$index]}
        if [ `echo $value | grep "^-" | wc -l` -ne 0 ];then
            #非特殊参数后面的值不是目标IP，不需要检查是否包含:
            name_rule="^-.*[a|A|b|B|d|D|f|h|L|n|O|q|r|R|U|v|V]$"
            check_ping_6=`echo $value | grep $name_rule | wc -l`
            continue
        fi
        if [ $check_ping_6 -ne 0 ] && [[ "$value" =~ ":" ]];then
            #目标IP包含:时，参数增加-6版本
            ping6 $@
            return $?
        fi
        check_ping_6=1
    done
    #目标IP不包含:时，参数不变化
    ping $@
    return $?
}

karbor_ping $@
