#!/bin/bash

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

# while the port is listening, publish to etcd
while [[ ! -z $(netstat -lnt | awk "\$6 == \"LISTEN\" && \$4 ~ \".$PORT\" && \$1 ~ \"$PROTO.?\"") ]] ; do
	etcdctl -C $ETCD set $ETCD_PATH/host $HOST --ttl $ETCD_TTL >/dev/null
	etcdctl -C $ETCD set $ETCD_PATH/port $PORT --ttl $ETCD_TTL >/dev/null
	sleep $(($ETCD_TTL/2)) # sleep for half the TTL
done

# if the loop quits, something went wrong
exit 1