#!/bin/bash
#
# This script is designed to be run inside the container
#

# configure etcd
export ETCD=${ETCD:-127.0.0.1:4001}
export ETCD_PATH=${ETCD_PATH:-/deis/controller}
export ETCD_TTL=${ETCD_TTL:-10}

# configure service discovery
export HOST=${HOST:-localhost}
export PORT=${PORT:-8000}
export PROTO=${PROTO:-tcp}

# wait for etcd to be available
until etcdctl -C $ETCD ls >/dev/null; do
	echo "waiting for etcd at $ETCD..."
	sleep $(($ETCD_TTL/2))  # sleep for half the TTL
done

# wait until etcd has discarded potentially stale values
sleep $(($ETCD_TTL+1))

# seed initial service configuration if necessary
$(dirname ${BASH_SOURCE[0]})/seed >/dev/null 2>&1

# wait for confd to run once and install initial templates
until confd -onetime -node $ETCD -config-file /app/confd.toml 2>/dev/null; do
	echo "waiting for confd to write initial templates..."
	sleep $(($ETCD_TTL/2))  # sleep for half the TTL
done

# wait for confd to populate all values
while grep -q '<no value>' /templates/confd_settings.py; do
       echo "waiting for confd to write all values..."
       confd -onetime -node $ETCD -config-file /app/confd.toml 2>/dev/null
       sleep $(($ETCD_TTL/2))  # sleep for half the TTL
done

# perform a one-time reload to install check config
/usr/local/bin/reload

# spawn the service in the background
$(dirname ${BASH_SOURCE[0]})/start &
SERVICE_PID=$!

# smart shutdown on SIGINT and SIGTERM
function on_exit() {
	kill -TERM $SERVICE_PID
	wait $SERVICE_PID 2>/dev/null
}
trap on_exit INT TERM

# spawn confd in the background to update services based on etcd changes
confd -node $ETCD -config-file /app/confd.toml &
CONFD_PID=$!

# wait for the service to become available
sleep 1 && while [[ -z $(netstat -lnt | awk "\$6 == \"LISTEN\" && \$4 ~ \".$PORT\" && \$1 ~ \"$PROTO.?\"") ]] ; do sleep 1; done

# as long as the service remains up, keep publishing to etcd with a TTL
$(dirname ${BASH_SOURCE[0]})/publish &

wait
