#!/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_TIMEOUT='90'
UWSGI_HEADERS='Connection:Keep-Alive'


cd /var/app

. /var/venv/bin/activate

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

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

# For uWSGI, Datadog tracing must be imported by uWSGI itself
if python -c "import ddtrace.auto" >/dev/null 2>&1; then
  DDTRACE_IMPORT="--import=ddtrace.auto"
else
  DDTRACE_IMPORT=""
fi

echo "Starting uWSGI with WSGI_PATH=${WSGI_PATH}"

exec uwsgi ${DDTRACE_IMPORT} \
  --log-4xx \
  --log-5xx \
  --log-ioerror \
  --log-x-forwarded-for \
  --lazy-apps \
  --cache2 name=uwsgi_cache,items=10 \
  --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}" \
  -t "${UWSGI_TIMEOUT}" \
  --http-keepalive \
  --add-header "${UWSGI_HEADERS}" \
  --buffer-size "${UWSGI_BUFFER_SIZE}"
