#!/bin/bash
set -e

BRIDGE=weave
CONTAINER_IFNAME=ethcr
MTU=65535

COMMAND=$1
IPADDR=$2
shift 2

# pre-create bridge so we can set the MTU
[ ! -d /sys/class/net/$BRIDGE ] && {
    ip link add dev $BRIDGE type bridge > /dev/null 2>&1
    ip link set dev $BRIDGE address $(od -txC -An -N6 /dev/random | tr \  : | tail -c+2)
    # attempting to set the bridge MTU to a high value directly
    # fails. Bridges take the lowest MTU of their interfaces. So
    # instead we create a temporary interface with the desired MTU,
    # attach that to the bridge, and then remove it again.
    ip link add name v${CONTAINER_IFNAME}du mtu $MTU type dummy
    ip link set dev v${CONTAINER_IFNAME}du master $BRIDGE
    ip link del dev v${CONTAINER_IFNAME}du
    ip link set dev $BRIDGE up
}

# We set the router name to the bridge mac since that is stable across
# re-creations of the containers.
#
# TODO use the mac of one of the physical host interfaces (eth0,
# wlan0, etc) so the name becomes stable across host restarts.
MACADDR=$(</sys/class/net/$BRIDGE/address)

case "$COMMAND" in
    launch)
        CONTAINER=$(docker run -d --name=weave -p 6783:6783/tcp -p 6783:6783/udp $WEAVE_DOCKER_ARGS zettio/weave -name $MACADDR $@)
        IFACE=eth0
        ;;
    run)
        CONTAINER=$(docker run -d $@)
        IFACE=$CONTAINER_IFNAME
        ;;
esac

pipework $BRIDGE -i $CONTAINER_IFNAME $CONTAINER $IPADDR 1>&2

docker-ns $CONTAINER ethtool -K $IFACE tx off > /dev/null

echo $CONTAINER
