#! /bin/bash
#qemu-ifup脚本
#**********创建临时网桥，判断是否存在**********
tmpbridge=ecoengine0
bExisted=0
btapExisted=0
bbridgerun=0
btaprun=0
for netdev in $(ls /sys/class/net/)
do
	#echo "net dev $netdev"
	if [ $netdev = $tmpbridge ];then
		bExisted=1
		echo "Found $tmpbridge"
	elif [ $netdev = $1 ];then
		echo "Found $1"
		btapExisted=1
	fi
done
if [ $bExisted -eq 0 ];then
	/opt/apps/tech.sanway.ecoengine/files/bin/brctl addbr $tmpbridge
else
#检测网卡是否起来,起来退出
	if [ -n "$(ip -f inet address show $tmpbridge)" ];then
		echo "$tmpbridge is up"
		bbridgerun=1
	fi
fi
if [ $bbridgerun -eq 0 ];then
	#**********启动网桥**********
	/opt/apps/tech.sanway.ecoengine/files/bin/brctl stp $tmpbridge on
	ip link set $tmpbridge up
	sleep 1
	#配置网桥地址及网关
	ip addr add 192.168.100.254/24 dev $tmpbridge
fi
if [ $btapExisted -eq 0 ];then
	echo "tap"
	/opt/apps/tech.sanway.ecoengine/files/bin/tunctl -b -t $1
	if [ -n "$(ip -f inet6 address show $1)" ];then
		echo "$1 is up"
		btaprun=1
	fi
fi
if [ $btaprun -eq 0 ];then
#**********启动虚拟网卡tap，添加虚拟网卡tap到网桥**********
	if [ -n "$1" ];then
		ip link set $1 up
		sleep 1
		/opt/apps/tech.sanway.ecoengine/files/bin/brctl addif $tmpbridge $1
	fi
fi
#**********设置nat模式，启动路由转发，关闭防火墙**********
#开启物理网卡的转发功能
sysctl -w net.ipv4.ip_forward=1
#配置iptables forward转发规则
iptables -t nat -A POSTROUTING -s 192.168.100.0/24 ! -d 192.168.100.0/24 -j MASQUERADE
#如果有防火墙的，放开防火墙
iptables -A FORWARD -s 0/0 -j ACCEPT
#显示网桥信息
/opt/apps/tech.sanway.ecoengine/files/bin/brctl show $tmpbridge
