#!/bin/bash

# check if all prequisites are installed before proceeding with setup.
# Pre-requisites:
# - Ubuntu 14+
# - Docker 1.6+
# - nsenter
# - bridge utils
# - ovs

errors=""
testval=$(lsb_release -a 2> /dev/null | grep "Distributor ID" | awk '{print $3}')
if [[ ${testval} != "Ubuntu" ]]; then
    errors=${errors}"- Not running Ubuntu release."
    errors=$errors"\n"
fi

testval=$(lsb_release -a 2> /dev/null | grep "Release" | awk '{print $2}')
if [[ ${testval} < "14" ]]; then
    errors=${errors}"- Ubuntu version is less than 14.0"
    errors=$errors"\n"
fi

testval=$(sudo docker version 2> /dev/null | grep "Server version" | awk '{print $3}')
if [[ ${testval} < "1.6" ]]; then
    errors=${errors}"- Docker daemon is not installed or version is less than 1.6"
    errors=$errors"\n"
fi

testval=$(which nsenter 2> /dev/null)
if [ -z ${testval} ]; then
    errors=${errors}"- nsenter is not installed"
    errors=$errors"\n"
fi

testval=$(which ovs-vsctl 2> /dev/null)
if [ -z ${testval} ]; then
    errors=${errors}"- ovs is not installed"
    errors=$errors"\n"
fi

testval=$(which brctl 2> /dev/null)
if [ -z ${testval} ]; then
    errors=${errors}"- bridge utils (brctl etc) are not installed"
    errors=$errors"\n"
fi

if [ -n "${errors}" ]; then
    echo "Following prerequisite checks failed:"
    echo -e ${errors}
    exit 1
fi

scriptdir=`dirname "$BASH_SOURCE"`
echo $scriptdir

# Create a linux bridge between containers
sudo brctl addbr br-em1
sudo brctl addbr br-em2
sudo ip link set br-em1 up
sudo ip link set br-em2 up

num_nodes=1
if [ -n "$CONTIV_NODES" ];
then
    num_nodes=$CONTIV_NODES
fi
echo "Num nodes = "$num_nodes

# Pull the docker image for hosts from docker-hub
# sudo docker build -t contiv/ubuntu $scriptdir
sudo docker images contiv/ubuntu | grep ubuntu
if [ $? != 0 ]; then
    sudo docker pull contiv/ubuntu
fi

# Pull ubuntu image for use within the docker hosts
sudo docker images ubuntu | grep ubuntu
if [ $? != 0 ]; then
    sudo docker pull ubuntu
fi

mkdir /tmp/ubuntu_image

sudo docker save -o /tmp/ubuntu_image/ubuntu-image.tar ubuntu

cluster=""
first_node_ip=""
for i in `seq 1 $num_nodes`;
do
    host="netplugin-node$i"
    echo "Starting $host"
    # godep modifies the host's GOPATH env variable, CONTIV_HOST_GOPATH
    # contains the unmodified path passed from the Makefile, use that
    # when it is defined.
    gopath=$GOPATH
    if [ -n "$CONTIV_HOST_GOPATH" ]; then
        gopath=$CONTIV_HOST_GOPATH
    fi
    sudo docker run -d -i -t --name $host --privileged -e CONTIV_DIND_HOST_GOPATH=$gopath \
        -e GOSRC=/gopath/src/ -v /var/lib/docker -v $gopath:/gopath -v /proc:/host/proc \
        -v /tmp/ubuntu_image:/ubuntu_image contiv/ubuntu bash \
        -c "/gopath/src/github.com/contiv/netplugin/scripts/dockerhost/start-service.sh & bash"
    sudo docker exec $host hostname $host
    sudo docker exec $host sh -c 'echo $(hostname -I | cut -d\  -f1) $(hostname) | tee -a /etc/hosts'
    # Create eth1
    sudo ip link add $i-int type veth peer name $i-ext
    sudo brctl addif br-em1 $i-ext
    sudo ip link set $i-ext up
    sudo ip link set netns $($scriptdir/docker-pid $host) dev $i-int
    sudo nsenter -t $($scriptdir/docker-pid $host) -n ip link set dev $i-int name eth1
    sudo nsenter -t $($scriptdir/docker-pid $host) -n ip link set eth1 up
    addr=$((10+$i-1))
    ip_addr="192.168.2."$addr"/32"
    echo "IP address = "$ip_addr
    sudo nsenter -t $($scriptdir/docker-pid $host) -n ip addr add $ip_addr dev eth1
    sudo nsenter -t $($scriptdir/docker-pid $host) -n ip route add "192.168.2.0/24" dev eth1
    # Create eth2
    sudo ip link add $i-int2 type veth peer name $i-ext2
    sudo brctl addif br-em2 $i-ext2
    sudo ip link set $i-ext2 up
    sudo ip link set netns $($scriptdir/docker-pid $host) dev $i-int2
    sudo nsenter -t $($scriptdir/docker-pid $host) -n ip link set dev $i-int2 name eth2
    sudo nsenter -t $($scriptdir/docker-pid $host) -n ip link set eth2 up
    if [ $i -gt "1" ]; then
	cluster=$cluster",";
    fi
    sudo docker exec $host service docker start
    sudo docker exec $host docker load -i /ubuntu_image/ubuntu-image.tar
    addr=$($scriptdir/docker-ip $host)
    cluster=$cluster$host"=http://"$addr":2380"
    if [ $i -eq 1 ]; then
        first_node_ip=$addr
    fi
done

sudo rm -rf /tmp/ubuntu_image

for i in `seq 1 $num_nodes`;
do
    host="netplugin-node$i"
    echo "Starting etcd on $host"
    addr=$($scriptdir/docker-ip $host)
    sudo docker exec -d $host etcd -name $host -data-dir /opt/etcd \
        -listen-client-urls http://0.0.0.0:2379,http://0.0.0.0:4001 \
        -advertise-client-urls http://$addr:2379,http://$addr:4001 \
        -initial-advertise-peer-urls http://$addr:2380 \
        -listen-peer-urls http://$addr:2380 -initial-cluster $cluster \
        -initial-cluster-state new
    echo "Starting consul on $host"
    consul_join_flag=""
    if [ $i -gt 1 ]; then
        consul_join_flag="-join $first_node_ip"
    fi
    consul_bootstrap_flag="-bootstrap-expect=3"
    if [ $num_nodes -lt 3 ]; then
        if [ $i -eq 1 ]; then
            consul_bootstrap_flag="-bootstrap"
        else
            consul_bootstrap_flag=""
        fi
    fi
   sudo docker exec -d $host consul agent -server $consul_join_flag $consul_bootstrap_flag \
       -bind=$addr -data-dir /opt/consul
done

sleep 5s
