#!/bin/sh

HOST=`hostname`
PREFIX=`echo ${HOST} | cut -c 1-4`
NNO=`echo ${HOST} | cut -c 5-6`

# Check if we are running on target node.
# TODO: convert to use regexp.

if [ "${PREFIX}" != "node" ]; then
	echo "$0: expected hostname 'nodeXX', got ${HOST}."
	exit 1
fi

if [ "${NNO}" -lt 15 -o "${NNO}" -gt 20 ]; then
	echo "$0: expected node number [15;20], got ${NNO}."
	exit 1
fi

# Now (probably) the $NNO contain valid decimal number in range [15;20].
# Pool of host IPs is [10.0.209.80/23;10.0.209.85/23].

# PHY looking to 10.0.208.0/23 network
ETH="eth1"
# Bridge name for both host PHY and VMPHYs.
BRD="br0"
# Host IP in 10.0.208.0/23 network
ETHIP="10.0.209.$((${NNO}+65))"
# Default GW in 10.0.208.0/23 network
ETHGW="10.0.208.1"
# TUN device name for tunnel nodeXX <-> nocnt server
TUN="tun0"
# Remote mgsu endpoint of tunnel (see also server part of setup)
TUN_REMOTE="192.168.74.242"
# Local and remote tunnel IPs
TUNIP_LOCAL="10.77.${NNO}.1"
TUNIP_REMOTE="10.77.${NNO}.2"
# Here also can be any other recursive nameserver. Rules of mgsu network
# filtering are no more for this host...
DNS="8.8.8.8"

# The most obvious network setup for virtualization.
# vSwitch for PHYs and VMPHYs.
brctl addbr ${BRD}
brctl addif ${BRD} ${ETH}
# The address should be specified for vSwitch, not PHY. 
ifconfig ${BRD} ${ETHIP}/23
ifconfig ${ETH} mtu 1500 up
ifconfig ${BRD} mtu 1500 up
# Assume that all 192.168 IPs are mgsu and reachable via $ETHGW.
# Note: nocnt internal network is 10.0.0.0/24 and perfectly
# reachable via tunnel.
route add -net 192.168.0.0/16 gw ${ETHGW}
# Set up endpoints of nodeXX <-> nocnt tunnel
ip tunnel add ${TUN} mode ipip remote ${TUN_REMOTE} local ${ETHIP} dev ${BRD}
# FIXME: this, probably, needs adjustment
ifconfig ${TUN} mtu 1500 up
# Set up IPs of tunnel
ifconfig ${TUN} ${TUNIP_LOCAL}/30 pointopoint ${TUNIP_REMOTE}
# No all traffic can be routed to nocnt.
route add default gw ${TUNIP_REMOTE}
# Here I'll going to significanly simplify the life by utilizing my own
# DNS records, so... no mgsu.ru any more )
if ! [ -f /etc/saved.conf.resolv ]; then
    cat /etc/resolv.conf > /etc/saved.conf.resolv
fi
echo "search kkatarn.ru" > /etc/resolv.conf
echo "nameserver ${DNS}" >> /etc/resolv.conf
