#!/bin/bash

set -e

usage() {
 echo "usage: start <number of machines> <provider(aws/vb)>"
 exit 1
}

if [ "$#" -ne 2 ]; then
 usage
fi

TOTAL="$1"
PROVIDER="$2"

if [ "$TOTAL" -lt 2 ]; then
 echo "number of machines should at least be 2"
 exit 1
fi

if [[ "$PROVIDER" != "aws" && "$PROVIDER" != "vb" ]]; then
 echo "provider $PROVIDER not supported yet"
 exit 1
fi

HERE=`dirname "$0"`
pushd $HERE >/dev/null

cat > conf/init.yml <<EOF
#generated by ../start, do not modify
Provider: $PROVIDER
MachineNumber: $TOTAL
EOF

mkdir -p ./files
# files/id_rsa, files/id_rsa.pub
if [ ! -f ./files/id_rsa ]; then 
 ssh-keygen -f ./files/id_rsa -t rsa -N '' &>/dev/null
fi

# files/workers
rm -f files/workers
for i in `seq 1 $((TOTAL-1))`; do
 echo "TachyonWorker${i}" >> files/workers
done
echo "TachyonMaster" >> files/workers

python bin/init.py $PROVIDER

# start machine without provisioning
FULL_PROVIDER_NAME=$PROVIDER
[[ "$FULL_PROVIDER_NAME" == "vb" ]] && FULL_PROVIDER_NAME=virtualbox
VUP="vagrant up --provider=$FULL_PROVIDER_NAME --no-provision"
[[ "$PROVIDER" == "aws" ]] && VUP="${VUP} --parallel"
$VUP

# files/hosts
# IPs are automatically assigned by vagrant
# hack to find out the assigned IPs by looking into vagrant's ssh config to 
# output of `ifconfig` is different in RHEL6.5 and RHEL7
#   inet:addr 127.0.0.1  VS. inet 127.0.0.1
# use `ip addr show` instead
rm -f files/hosts
IFACE=eth0
[[ "$PROVIDER" == "vb" ]] && IFACE=eth1 # because of dhcp
for host in `cat files/workers`; do
 echo "looking up IP of $host..."
 IP=`vagrant ssh $host -c "ip addr show $IFACE | grep -w inet" | grep -w inet | awk '{print $2}' | cut -d'/' -f1`
 echo "IP for $host is $IP"
 echo "$IP ${host}" >> files/hosts
done

# provision
vagrant provision

# show master IP
if [[ "$?" == "0" ]]; then
 HERE=`dirname $0`
 pushd $HERE > /dev/null
 if [[ "$PROVIDER" == "aws" ]]; then
  master=`cat ${HERE}/.vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory | grep Master | cut -d' ' -f2 | cut -d'=' -f2`
 else
  master=`tail -n 1 $HERE/files/hosts | cut -d' ' -f1`
 fi
 purple='\033[1;35m'
 no_color='\033[0m'
 echo -e ">>> ${purple}TachyonMaster public IP is ${master}${no_color} <<<"
 echo -e ">>> ${purple}visit default port of the web UI of what you deployed${no_color} <<<"
fi

popd >/dev/null
