#!/bin/bash
set -e
# Modeled closely after flask portion of amazon/aws-eb-python:3.4.2-onbuild-3.5.1 entrypoint script

UWSGI_UID='uwsgi'
UWSGI_GID='uwsgi'

UWSGI_BUFFER_SIZE='12288'
UWSGI_TIMEOUT='90'
UWSGI_HEADERS='Connection:Keep-Alive'

UWSGI_WORKERS="${UWSGI_WORKERS:-50}"
UWSGI_CHEAPER="${UWSGI_CHEAPER:-15}"
UWSGI_CHEAPER_ALGO="${UWSGI_CHEAPER_ALGO:-spare}"
UWSGI_CHEAPER_STEP="${UWSGI_CHEAPER_STEP:-5}"
UWSGI_CHEAPER_INITIAL="${UWSGI_CHEAPER_INITIAL:-30}"
UWSGI_CHEAPER_OVERLOAD="${UWSGI_CHEAPER_OVERLOAD:-15}"
UWSGI_RELOAD_MERCY="${UWSGI_RELOAD_MERCY:-120}"
UWSGI_WORKER_RELOAD_MERCY="${UWSGI_WORKER_RELOAD_MERCY:-120}"


cd /var/app

# Flask support
if cat requirements.txt | 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

# TODO: Don't even execute with ddtrace-run
# ddtrace-py docs are explicit that it doesn't work with uwsgi:
# https://ddtrace.readthedocs.io/en/stable/advanced_usage.html#uwsgi
DDTRACE_BINARY=$(whereis ddtrace-run | cut -d ' ' -f 2)
if [ -x ${DDTRACE_BINARY} ]; then
 ${DDTRACE_BINARY} uwsgi --log-4xx --log-5xx --log-ioerror --log-x-forwarded-for --disable-logging --cache2 name=uwsgi_cache,items=10 --http :8080 --chdir /var/app --wsgi-file ${WSGI_PATH} ${UWSGI_MODULE} --master --uid ${UWSGI_UID} --gid ${UWSGI_GID} -t ${UWSGI_TIMEOUT} --http-keepalive --add-header ${UWSGI_HEADERS} --buffer-size ${UWSGI_BUFFER_SIZE} --enable-threads --lazy-apps --import=ddtrace.bootstrap.sitecustomize --workers ${UWSGI_WORKERS} --cheaper ${UWSGI_CHEAPER} --cheaper-algo ${UWSGI_CHEAPER_ALGO} --cheaper-initial ${UWSGI_CHEAPER_INITIAL} --cheaper-step ${UWSGI_CHEAPER_STEP} --cheaper-overload ${UWSGI_CHEAPER_OVERLOAD} --reload-mercy ${UWSGI_RELOAD_MERCY} --worker-reload-mercy ${UWSGI_WORKER_RELOAD_MERCY}
else
 uwsgi --log-4xx --log-5xx --log-ioerror --log-x-forwarded-for --disable-logging --cache2 name=uwsgi_cache,items=10 --http :8080 --chdir /var/app --wsgi-file ${WSGI_PATH} ${UWSGI_MODULE} --master --uid ${UWSGI_UID} --gid ${UWSGI_GID} -t ${UWSGI_TIMEOUT} --http-keepalive --add-header ${UWSGI_HEADERS} --buffer-size ${UWSGI_BUFFER_SIZE} --enable-threads --lazy-apps --import=ddtrace.bootstrap.sitecustomize --workers ${UWSGI_WORKERS} --cheaper ${UWSGI_CHEAPER} --cheaper-algo ${UWSGI_CHEAPER_ALGO} --cheaper-initial ${UWSGI_CHEAPER_INITIAL} --cheaper-step ${UWSGI_CHEAPER_STEP} --cheaper-overload ${UWSGI_CHEAPER_OVERLOAD} --reload-mercy ${UWSGI_RELOAD_MERCY} --worker-reload-mercy ${UWSGI_WORKER_RELOAD_MERCY}
fi
