#!/bin/bash

#TODO: Generating a config file rather than args so etcd-bootstrap can run as a
#      completely separate unit from etcd

STATE=/var/lib/etcd
ARGS="-f -data-dir $STATE -bind-addr 0.0.0.0"

ARGS="${ARGS} -peer-election-timeout 1200"

BOOTSTRAP_PEERS="/var/run/etcd/bootstrap.config"
BOOTSTRAP_DISCO="/var/run/etcd/bootstrap.disco"

META_URL="http://169.254.169.254/latest"
MY_IP=$(curl --fail -s $META_URL/meta-data/local-ipv4)
if [ $? -ne 0 ]; then
    echo "Request to meta-data service failed" >&2
    exit 1
fi

ARGS="${ARGS} -name ${MY_IP} -addr ${MY_IP}:4001 -peer-addr ${MY_IP}:7001 -peer-bind-addr 0.0.0.0"

if [ -e $BOOTSTRAP_DISCO ]; then
	DISCOVERY_URL="$(cat $BOOTSTRAP_DISCO)"
	ARGS="${ARGS} -discovery ${DISCOVERY_URL}"

elif [ -e $BOOTSTRAP_PEERS ]; then
	IPS=$(grep -v $MY_IP $BOOTSTRAP_PEERS | grep -v '^$' | sed 's/$/:7001/'| tr '\n' ','| sed 's/^,//' | sed 's/,$//')
	if [ -n "$IPS" ]; then
		ARGS="${ARGS} -C ${IPS}"
	fi
fi

exec /usr/bin/etcd $ARGS
