#! /bin/bash

# bridge und tap devices for kvm on notebook

user=$1

if [ X$user = X ]; then
    echo "Give user name as first parameter"
    exit 99
fi


tapnum=30
dev=eth0

aptitude -y install qemu-kvm qemu-utils cu bridge-utils

#hostname faiserver

# MAN KANN DIE ADRESSE AUCH AUF lo legen: ip addr add 192.168.33.250/24 dev lo
# dann muss der DHCP aber auch auf lo horschen. Vielleicht doch keine gute Idee.

#ifdown eth0

ip addr flush eth0            # remove IP address of real eth0
ip link set eth0 down  
ip link set eth0 name reth0   # rename the original eth0 to reth0 (real eth0)
#ip link set reth0 up

brctl addbr eth0
brctl addif eth0 reth0        # add original eth0 to the bridge

#ip addr add 192.168.33.250/24 brd + dev $dev

# bring up the newly created bridge, now it gets an IP address
ip link set $dev up

# create the tap devices tap1, tap2,...
# and add them to the bridge

for ((i=1;i<=tapnum;i++)); do
    [ -f /sys/class/net/tap$i/address ] && continue
    ip tuntap add dev tap$i mode tap user $user
    # since a bridge always uses the smalest/lowest MAC address, make sure the tap devices have a high MAC address
    # otherwise the dhcp call will not use the MAC address of eth0
    # change MAC address, so if begins with fX:
    mac=`sed -e 's/^./f/' /sys/class/net/tap$i/address`
    ip link set tap$i address $mac
    brctl addif eth0 tap$i          # add device to the bridge
    ip link set tap$i up
done

ip link set reth0 up
ip link set eth0 up


echo chmod a+rw /dev/kvm
