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

# fail hard and fast even on pipelines
set -eo pipefail

# set debug based on envvar
[[ $DEBUG ]] && set -x

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

# 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
if ! etcdctl -C $ETCD ls $ETCD_PATH >/dev/null 2>&1 ; then
	etcdctl -C $ETCD mkdir $ETCD_PATH/users >/dev/null 2>&1 || true
fi

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

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

# remove any pre-existing docker.sock
test -e /var/run/docker.sock && rm -f /var/run/docker.sock

# spawn a docker daemon to run builds
docker -d --bip=172.19.42.1/16 &
DOCKER_PID=$!

# wait for docker to start
while [[ ! -e /var/run/docker.sock ]]; do
  sleep 1
done

# pull required images
docker pull deis/slugbuilder:latest
docker pull deis/slugrunner:latest

# start an SSH daemon to process `git push` requests
/usr/sbin/sshd -D -e &
SSHD_PID=$!

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

# publish the service to etcd using the injected HOST and PORT
if [[ ! -z $PUBLISH ]]; then

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

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

	# while the port is listening, publish to etcd
	while [[ ! -z $(netstat -lnt | awk "\$6 == \"LISTEN\" && \$4 ~ \".$PUBLISH\" && \$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

fi

wait
