#!/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/logs}
export ETCD_TTL=${ETCD_TTL:-10}

# fix perms on log directory
chmod 755 /var/log/deis

# spawn the service in the background
/go/bin/syslogd &
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

echo deis-logger running...

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

    # configure service discovery
    PORT=${PORT:-514}
    PROTO=${PROTO:-udp}

    set +e

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

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

    # if the loop quits, something went wrong
    exit 1

fi

wait
