# usage: 
# loads /etc/xgurulla/config
#
# N the number of the instance
# NETWORK_NAME
# SERVER_NAME

MAX_INSTANCES=10
FIRST_VLAN=100
LAST_VLAN=200

. /etc/xgurulla/config

common_setup()
{
	echo $HOSTNAME > /etc/hostname
	echo 127.0.0.1 $HOSTNAME ${HOSTNAME%%.*} > /etc/hosts
	hostname $HOSTNAME
	touch /root/.hushlogin
	export DEBIAN_FRONTEND=noninteractive
    perl -p -i -e 's/universe/universe multiverse/' /etc/apt/sources.list
	pkill apt-get ; pkill dpkg ; sleep 5; pkill apt-get; pkill dpkg ; sleep 5
	dpkg --configure -a
     	apt-get -q -y update
        apt-get -q -y install dynamips openvpn bridge-utils rsync vlan unzip screen &
	while ps waux | grep -q apt-get
	do
		sleep 5
		if ps aux | grep -v grep | grep -q dpkg.*defunct
		then
	pkill apt-get ; pkill dpkg ; sleep 5; pkill apt-get; pkill dpkg ; sleep 5
			dpkg --configure -a
    			apt-get -q -y install dynamips openvpn bridge-utils rsync vlan unzip screen &
		fi
	done
}

server_bridges_setup()
{
    brctl addbr br0
    ip link set br0 up
    ifconfig br0 promisc
    for i in `seq 0 $MAX_INSTANCES`
    do
        brctl addif br0 tap$i
        ip link set tap$i up
    done
}

vlans_setup()
{
    interface=$1
    ip link set $interface up
    vconfig set_name_type VLAN_PLUS_VID_NO_PAD
    for i in `seq $FIRST_VLAN $LAST_VLAN`
    do
        vconfig add $interface $i
	ip link set vlan$i up
        brctl addbr br$i 
        ip link set br$i up
        ifconfig br$i promisc
	brctl addif br$i vlan$i
    done
}

server_setup()
{
    cd /etc/openvpn
    openvpn --genkey --secret static.key
    for i in `seq 0 $MAX_INSTANCES`
    do
    cat <<EOF > server$i.conf
port $((22000+i))
secret static.key
dev tap$i
EOF
    done
    /etc/init.d/openvpn restart
}

client_setup()
{
    cd /etc/openvpn
    scp $SERVER:/etc/openvpn/static.key .
    cat <<EOF > client.conf
port $((22000+N))
secret static.key
remote $SERVER
dev tap0
EOF
    /etc/init.d/openvpn restart
}

copy_files_to_server()
{
    mkdir /mnt2
    mount /dev/sdb1 /mnt2
    rsync -a /mnt2/ /mnt/
    umount /mnt2
    rmdir /mnt2
    
    #mkdir /mnt/ios
    #cd /mnt/ios
    #wget http://igor.chub.in/tmp/ios
    #unzip ios
}

copy_files_from_server()
{
    rsync -a $SERVER:/mnt/ /mnt/
}

if [ "$1" = vlans_setup ]
then
   [ "$N" = 0 ]  && vlans_setup br0 || vlan_setup tap0
   exit 0
fi

if [ "$1" = server_bridges_setup ]
then
   [ "$N" = 0 ]  && server_bridges_setup
   exit 0
fi


if [ "$N" = 0 ] 
then
    common_setup
    server_setup
    server_bridges_setup
    vlans_setup br0
    copy_files_to_server
else
    common_setup
    client_setup
    vlans_setup tap0
    copy_files_from_server
fi