#!/bin/bash

apt install miniupnpc -y  >/dev/null 2>&1

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 `netstat  -nlp |grep -E '0.0.0.0:8888|0.0.0.0:8889' |awk '{print $4}' |awk -F: '{print $2}'`
        do

        j=`cat /tmp/upnpc_L.txt |grep -w ${IP}:${SPORT} |wc -l`

        if [ $j -eq  1 ]
        then
                i=5
        else
                i=0
        fi

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

                        if [ $? -eq 0 ]
                        then
                                break;
                        else
                                sleep 1
                                i=$i+1
                                echo "$IP ERROR"
                        fi

                done
        done
done
