#!/bin/bash
UWSGI_NUM_PROCESSES='4'
UWSGI_NUM_THREADS='2'
UWSGI_UID='uwsgi'
UWSGI_GID='uwsgi'
UWSGI_BUFFER_SIZE='12288'
UWSGI_TIMEOUT='90'
UWSGI_HEADERS='Connection:Keep-Alive'

cd /var/app

# Flask support
if cat Pipfile.lock | grep -q -i Flask && [ -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

DDTRACE_BINARY=$(whereis ddtrace-run | cut -d ' ' -f 2)
if [ -x ${DDTRACE_BINARY} ]; then
  ${DDTRACE_BINARY} pipenv run uwsgi \
    --lazy-apps \
    --thunder-lock \
    --reuse-port \
    --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} \
    --reuse-port
else
  pipenv run uwsgi \
    --lazy-apps \
    --thunder-lock \
    --reuse-port \
    --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}
fi
