#!/bin/bash

if test $# -ne 3; then
	echo "Usage: $0 <peer-directory> <experiment-config> <branch>"
	exit 1
fi
PEERS=$1
EXPERIMENT_CONFIG=$2
BRANCH=$3
source $EXPERIMENT_CONFIG # $DISPERSY_ARGS

cd ${PEERS}
PEERS=$(pwd)

function get_network_interface() {
    # Ethernet interfaces
    iface_no=0
    while test $iface_no -lt 10; do
    	ip address show dev eth$iface_no 2>/dev/null | grep 'inet ' &>/dev/null
    	if test $? -eq 0; then
    		echo eth$iface_no
    		return
    	fi
    	iface_no=$[$iface_no + 1]
    done

    # Bridge interfaces - apparently, they are being actively used
    iface_no=0
    while test $iface_no -lt 10; do
    	ip address show dev br$iface_no 2>/dev/null | grep 'inet ' &>/dev/null
    	if test $? -eq 0; then
    		echo br$iface_no
    		return
    	fi
    	iface_no=$[$iface_no + 1]
    done

    # InfiniBand interfaces
    iface_no=0
    while test $iface_no -lt 10; do
    	ip address show dev ib$iface_no 2>/dev/null | grep 'inet ' &>/dev/null
    	if test $? -eq 0; then
    		echo ib$iface_no
    		return
    	fi
    	iface_no=$[$iface_no + 1]
    done
}

# find the first eth interface with an IP set (test eth0-eth9)
iface=$(get_network_interface)

# fallback to the 'loopback' interface if nothing found
if test -z $iface; then
    echo "* No public eth/ib interface found. Using loopback interface (peer might not be connectable)" >&2
    iface="lo"
fi

# determine the IP of the usable interface
MY_IP=$(ip address show dev $iface | grep 'inet ' | awk -F '[/ ]' '{print $6}')

export PYTHONPATH=${BRANCH}:/home/mbardac/3rd-party/lib/python2.6/site-packages:$PYTHONPATH
export LD_LIBRARY_PATH=/home/mbardac/3rd-party/lib:$LD_LIBRARY_PATH

config="$(${BRANCH}/das4-config-sync-client.py 130.161.7.3 $MY_IP)"
MY_ID=$(echo $config | cut -d' ' -f1)
STARTING_TIMESTAMP=$(echo $config | cut -d' ' -f2)
source $EXPERIMENT_CONFIG # reload config with the new STARTING_TIMESTAMP

# run node
cd ${MY_ID}
MYDIR=$(pwd)

# cleanup
rm -rf ${MYDIR}/output

# move config files
mv /tmp/$USER/dispersy/peer_${MY_ID}.conf ${MYDIR}/data/peer.conf

#read -p "Press the any key to continue..."

MY_PORT=$(awk -F'[ ]' '{ print $3 }' data/peer.conf)

echo "Starting Dispersy client #$MY_ID on $MY_IP:$MY_PORT"

DISPERSY_DIR=/tmp/$USER/dispersy/$MY_ID
mkdir -p $DISPERSY_DIR/data
cp -a ${MYDIR}/data/* $DISPERSY_DIR/data/
cp ${DPRINT_CONF} $DISPERSY_DIR/dprint.conf

cd $DISPERSY_DIR

echo python ${BRANCH}/Tribler/Main/dispersy.py --ip $MY_IP --port $MY_PORT $DISPERSY_ARGS
#python ${BRANCH}/Tribler/Main/dispersy.py --ip $MY_IP --port $MY_PORT $DISPERSY_ARGS
python -O ${BRANCH}/Tribler/Main/dispersy.py --ip $MY_IP --port $MY_PORT $DISPERSY_ARGS

#read -p "Press the any key to close..."
