#!/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_PORT=${ETCD_PORT:-4001}
export ETCD="$HOST:$ETCD_PORT"
export ETCD_PATH=${ETCD_PATH:-/deis/database}
export ETCD_TTL=${ETCD_TTL:-10}

# initialize data volume
if [[ ! -d /var/lib/postgresql/9.3/main ]]; then
  mkdir -p /var/lib/postgresql/9.3
  chown -R postgres:postgres /var/lib/postgresql
  sudo -u postgres /usr/lib/postgresql/9.3/bin/initdb -D /var/lib/postgresql/9.3/main
fi

# wait for etcd to be available
until etcdctl --no-sync -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))

function etcd_safe_set {
  if ! etcdctl --no-sync -C $ETCD get $ETCD_PATH/$1 >/dev/null 2>&1; then
    etcdctl --no-sync -C $ETCD set $ETCD_PATH/$1 $2 >/dev/null
  fi
}

etcd_safe_set engine postgresql_psycopg2
etcd_safe_set adminUser ${PG_ADMIN_USER:-postgres}
etcd_safe_set adminPass ${PG_ADMIN_PASS:-changeme123}
etcd_safe_set user ${PG_USER_NAME:-deis}
etcd_safe_set password ${PG_USER_PASS:-changeme123}
etcd_safe_set name ${PG_USER_DB:-deis}

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

# run the service in the background
sudo -i -u postgres /usr/lib/postgresql/9.3/bin/postgres \
                    -c config-file=${PG_CONFIG:-/etc/postgresql/9.3/main/postgresql.conf} \
                    -c listen-addresses=${PG_LISTEN:-*} &

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 ~ \".5432\" && \$1 ~ \"tcp.?\"") ]] ; do sleep 1; done

# perform a one-time reload to populate database entries
/usr/local/bin/reload

echo deis-database running...

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

	# configure service discovery
	PORT=${PORT:-5432}
	PROTO=${PROTO:-tcp}

	set +e

	# 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 --no-sync -C $ETCD set $ETCD_PATH/host $HOST --ttl $ETCD_TTL >/dev/null
		etcdctl --no-sync -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
