#!/bin/bash

# Copyright (C) 2016 NIWA Hideyuki

FULCONDRIVER=`fulcon driver-name`
PATH=/usr/lib/fulcon/driver/$FULCONDRIVER:/usr/lib/fulcon/lib:$PATH
FULCONDIR=/var/lib/fulcon

usage()
{
	echo "usage: net-nic-add NET_DEVICE"
}

lsdir() {
  ls -f --ind=none $1 | sed '/^\.\{1,2\}$/d'
}


if [ $# -ne 1 ]; then
	usage
	exit -1
fi
if [ $# -eq 1 -a x"$1" == x"net-nic-add" ]; then
	usage
	exit -1
fi

NETDEV=$1
ip a show $NETDEV >& /dev/null
if [ $? -ne 0 ]; then
	echo "error: can't" $NETDEV "does not exist"
	exit -1
fi

if [ x"`brctl show | egrep $NETDEV | awk '{print $NF}'`" == x"$NETDEV" ]; then
	echo "error: $NETDEV has already been allocated in the bridge. "
	exit -1
fi

IP1=`ip a show $NETDEV | egrep "inet " | awk '{print $2}'`
IP1G=`net-ipv4 -g $IP1`
for i in `lsdir $FULCONDIR/br`
do
	if [ x"$NETDEV" == x"$i" ]; then
		continue
	fi

	IP2=`ip a show $i | egrep "inet " | awk '{print $2}'`
	IP2G=`net-ipv4 -g $IP2`
	if [ x"$IP1G" == x"$IP2G" ]; then
		IP2N=`echo $IP2G | sed -e 's/.1$/.0/'`
		echo "error: $IP2N network has already been added."
		exit -1
	fi
done

BRNO="-1"
IPMASK=`ip a show $NETDEV | egrep "inet " | awk '{print $2}'`
IPG=`net-ipv4 -g $IPMASK`
# 
for i in `brctl show | egrep fulcon | awk '{print $1}'`
do
	BIP=`ip a show $i | egrep "inet " | awk '{print $2}'`
	BIPG=`net-ipv4 -g $BIP`
	BNO=`echo $i | sed -e "s/fulcon//"`
	if [ x"$IPG" == x"$BIPG" ]; then
		BRNO=$BNO
		break
	fi
done

if [ $BRNO -eq -1 ]; then
	BRNO=1
	while : 
	do
		ip a show fulcon$BRNO >& /dev/null
		if [ $? -ne 0 ]; then
			break
		fi
		BRNO=`expr $BRNO + 1`
	done
	brctl addbr fulcon$BRNO
	ip link set fulcon$BRNO up
	echo "generated new BRIDGE : fulcon"$BRNO
fi

# clear ip
while :
do
	IP=`ip a show fulcon$BRNO | egrep "inet " | awk '{print $2}'`
	if [ x"$IP" == x"" ]; then
		break
	fi
	ip addr del $IP dev fulcon$BRNO
done

# set ip address for bridge, add interface to net_device
ip addr add $IPMASK dev fulcon$BRNO
brctl addif fulcon$BRNO $NETDEV

# set BR MAC
#MAC=`ip addr show fulcon$BRNO | egrep link/ether | awk '{print $2}' | awk -F : '{printf "52:54:00:%2s:%2s:%2s",$4,$5,$6}'`
#ip link set fulcon$BRNO address $MAC

# delete address of nic
#ip addr del $IPMASK dev $NETDEV
#ifconfig $NETDEV 0.0.0.0 up

# set promisc mode to net_device
ip link set $NETDEV promisc on

# when system is reboot, this setup is setting again
mkdir -p $FULCONDIR/br
echo "net-nic-add $NETDEV" > $FULCONDIR/br/$NETDEV

echo "net-nic-add $NETDEV"

exit 0
