#!/bin/bash

# Modeled closely after flask portion of amazon/aws-eb-python:3.4.2-onbuild-3.5.1 entrypoint script

UWSGI_NUM_PROCESSES='1'
UWSGI_NUM_THREADS='15'
UWSGI_UID='uwsgi'
UWSGI_GID='uwsgi'
# increase header buffer size if one is seeing 502s & 'invalid request block size' errors in uwsgi log
UWSGI_BUFFER_SIZE='12288'
UWSGI_HEADERS='Connection:Keep-Alive'


cd /var/app

. bin/activate

# Flask support
if cat requirements.txt | grep -q -i Flask && [ -z "${WSGI_MODULE}" ]; then
  UWSGI_MODULE='--module main:app'
fi

# defaulting to application.py if not explicitly set
[ -z "${WSGI_PATH}" ] && WSGI_PATH=main.py

wait_for_port() {
  local name="$1" host="$2" port="$3"
  local j=0
  while ! nc -z "$host" "$port" >/dev/null 2>&1 < /dev/null; do
    j=$((j+1))
    if [ $j -ge $TRY_LOOP ]; then
      echo >&2 "$(date) - $host:$port still not reachable, giving up"
      exit 1
    fi
    echo "$(date) - waiting for $name... $j/$TRY_LOOP"
    sleep 5
  done
}

DDTRACE_BINARY=$(whereis ddtrace-run | cut -d ' ' -f 2)
if [ -x ${DDTRACE_BINARY} ]; then
  ${DDTRACE_BINARY} uwsgi --http :8080 --chdir /var/app --wsgi-file ${WSGI_PATH} ${UWSGI_MODULE} --master --processes ${UWSGI_NUM_PROCESSES} --threads ${UWSGI_NUM_THREADS} --uid ${UWSGI_UID} --gid ${UWSGI_GID} --buffer-size ${UWSGI_BUFFER_SIZE} --http-keepalive --add-header ${UWSGI_HEADERS}
else
  uwsgi --http :8080 --chdir /var/app --wsgi-file ${WSGI_PATH} ${UWSGI_MODULE} --master --processes ${UWSGI_NUM_PROCESSES} --threads ${UWSGI_NUM_THREADS} --uid ${UWSGI_UID} --gid ${UWSGI_GID} --buffer-size ${UWSGI_BUFFER_SIZE} --http-keepalive --add-header ${UWSGI_HEADERS}
fi
