#!/bin/bash

apt-get install miniupnpc

GW=`route -n |grep macvlan4 |grep UG |head -1 |awk '{print $2}'`

if [ "x${GW}" == "x" ];then
    GW='10.0.0.1'
fi

UPNPC="upnpc -u http://${GW}:1900/rootDesc.xml"

${UPNPC} -L >/tmp/upnpc_L.txt

for IP in `ifconfig  |grep macvlan -A 1 |grep inet|grep 'inet 10' |awk '{print $2}'`;do
    for SPORT in $(echo "8888 8889 9928");do

        # 查询upnp存量配置
        j=`cat /tmp/upnpc_L.txt |grep -w ${IP}:${SPORT} |wc -l`
        if [ "$j" -ne 0 ];then
            i=5
        else
            i=0
        fi

        # 最大尝试5次
        while (( i<5 ));do
            PORT=$((${RANDOM}%30000+15000))
            echo "${UPNPC} -a ${IP} ${SPORT} ${PORT} TCP"
            echo "${UPNPC} -a ${IP} ${SPORT} ${PORT} UDP"
            ${UPNPC} -a ${IP} ${SPORT} ${PORT} TCP >/tmp/upnpc.log 2>&1
            ${UPNPC} -a ${IP} ${SPORT} ${PORT} UDP >/tmp/upnpc.log 2>&1

            # 配置成功跳出
            if [ $? -eq 0 ];then
                break;
            # 配置失败+1重试
            else
                sleep 1
                i=$i+1
                echo "$IP ERROR"
            fi
        done
    done
done
