#!/bin/bash

set -eo pipefail

CONF_DIR=/var/vcap/data/tcp_router/config
HAPROXY_PID_FILE="${CONF_DIR}/haproxy.pid"
PATH=/var/vcap/packages/haproxy/bin:$PATH
DAEMON=$(which haproxy)
CONFIG="${CONF_DIR}/haproxy.conf"

TIMESTAMP=$(which date)

test -x "${DAEMON}"
test -f "${CONFIG}"

RETVAL=0

remove_haproxy_pid() {
    rm -f "${HAPROXY_PID_FILE}"
}

start_haproxy() {
    status_haproxy
    if [ "${RETVAL}" = 0 ]; then
        echo "HAProxy is currently running"
    else
        RETVAL=0
        echo "$("${TIMESTAMP}"): Starting HAProxy"
        set +e
        "${DAEMON}" -f "${CONFIG}" -D -p "${HAPROXY_PID_FILE}" 0<&-
        RETVAL=$?
        set -e
        case "${RETVAL}" in
            0)
                echo "$("${TIMESTAMP}"): Successfully started HAProxy"
                ;;
            *)
                echo "$("${TIMESTAMP}"): Errored starting HAProxy"
                echo "$("${TIMESTAMP}"): Errored starting HAProxy" >&2
                echo "$("${TIMESTAMP}"): Removing stale PID file for HAProxy"
                remove_haproxy_pid
                echo "FAILED - check logs"
                RETVAL=1
                ;;
        esac
    fi
}

# RETVAL = 0 if running, != 0 if stopped
status_haproxy() {
    if [ -f "${HAPROXY_PID_FILE}" ]; then
        RETVAL=0
        set +e
        for pid in $(cat "${HAPROXY_PID_FILE}"); do
            kill -0 "${pid}" > /dev/null 2>&1 || RETVAL=3
        done
        kill -0 $(cat "${HAPROXY_PID_FILE}") > /dev/null 2>&1
        if [ $? != 0 ]; then
            RETVAL=3
        fi
        set -e
    else
        RETVAL=1
    fi
}

start_haproxy

set +e
  host <%= p("dns_health_check_host") %>
  if [[ "0" != "$?" ]]; then
    echo "DNS is not up"
    exit 1
  fi
set -e

exec /var/vcap/packages/tcp_router/bin/cf-tcp-router\
  -debugAddr=<%= p("tcp_router.debug_address") %> \
  -logLevel=<%= p("tcp_router.log_level") %> \
  -timeFormat=rfc3339 \
  -tcpLoadBalancerConfig="${CONFIG}" \
  -tcpLoadBalancerBaseConfig="/var/vcap/jobs/tcp_router/config/haproxy.conf.template" \
  -config="/var/vcap/jobs/tcp_router/config/tcp_router.yml" \
  -tcpLoadBalancerStatsUnixSocket="${CONF_DIR}/haproxy.sock" \
  -haproxyReloader="/var/vcap/jobs/tcp_router/bin/haproxy_reloader" \
  -statsCollectionInterval=<%= p("tcp_router.tcp_stats_collection_interval") %> \
  -dropsondePort=<%=p("metron.port") %> \
  -routingGroupCheckExit=<%= p("tcp_router.fail_on_router_port_conflicts") %>

while kill -0 "$(cat ${HAPROXY_PID_FILE})"; do
  sleep 1
done
