#!/bin/bash

#!/bin/bash

UWSGI_UID='uwsgi'
UWSGI_GID='uwsgi'

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

UWSGI_WORKERS="${UWSGI_WORKERS:-15}"
UWSGI_CHEAPER="${UWSGI_CHEAPER:-5}"
UWSGI_CHEAPER_ALGO="${UWSGI_CHEAPER_ALGO:-spare}"
UWSGI_CHEAPER_OVERLOAD="${UWSGI_CHEAPER_OVERLOAD:-5}"
UWSGI_CHEAPER_STEP="${UWSGI_CHEAPER_STEP:-5}"
UWSGI_CHEAPER_INITIAL="${UWSGI_CHEAPER_INITIAL:-5}"

cd /var/app

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

DDTRACE_BINARY=$(whereis ddtrace-run | cut -d ' ' -f 2)
echo "DD trace= ${DDTRACE_BINARY}"

if [ -x ${DDTRACE_BINARY} ]; then
  ${DDTRACE_BINARY} uwsgi \
    --cache2 name=uwsgi_cache,items=10 \
    --http :8080 \
    --chdir /var/app \
    --wsgi-file ${WSGI_PATH} \
    --module application:app \
    --master \
    --uid ${UWSGI_UID} \
    --gid ${UWSGI_GID} \
    -t ${UWSGI_TIMEOUT} \
    --http-keepalive \
    --add-header ${UWSGI_HEADERS} \
    --buffer-size ${UWSGI_BUFFER_SIZE} \
    --enable-threads \
    --workers ${UWSGI_WORKERS} \
    --cheaper ${UWSGI_CHEAPER} \
    --cheaper-algo ${UWSGI_CHEAPER_ALGO} \
    --cheaper-initial ${UWSGI_CHEAPER_INITIAL} \
    --cheaper-step ${UWSGI_CHEAPER_STEP} \
    --harakiri-verbose \
    --lazy-apps \
    --import=ddtrace.auto \
    --enable-threads \
    --py-call-uwsgi-fork-hooks
else
  uwsgi \
    --cache2 name=uwsgi_cache,items=10 \
    --http :8080 \
    --chdir /var/app \
    --wsgi-file ${WSGI_PATH} \
    --module application:app \
    --master \
    --uid ${UWSGI_UID} \
    --gid ${UWSGI_GID} \
    -t ${UWSGI_TIMEOUT} \
    --http-keepalive \
    --add-header ${UWSGI_HEADERS} \
    --buffer-size ${UWSGI_BUFFER_SIZE} \
    --enable-threads \
    --workers ${UWSGI_WORKERS} \
    --cheaper ${UWSGI_CHEAPER} \
    --cheaper-algo ${UWSGI_CHEAPER_ALGO} \
    --cheaper-initial ${UWSGI_CHEAPER_INITIAL} \
    --cheaper-step ${UWSGI_CHEAPER_STEP} \
    --harakiri-verbose \
    --lazy-apps \
    --import=ddtrace.auto \
    --enable-threads \
    --py-call-uwsgi-fork-hooks
fi
