#!/bin/bash
UWSGI_UID='uwsgi'
UWSGI_GID='uwsgi'

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

# snowflake-connector-python 4.4.0 stats ~/.snowflake at import time; Python 3.11 propagates
# PermissionError from Path.exists() when /root is mode 700 and process runs as uwsgi user.
export SNOWFLAKE_HOME="${SNOWFLAKE_HOME:-/var/app/.snowflake}"

UWSGI_WORKERS="${UWSGI_WORKERS:-250}"
UWSGI_CHEAPER="${UWSGI_CHEAPER:-15}"
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:-15}"

cd /var/app/env

. bin/activate

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

# ddtrace is loaded via `--import=ddtrace.auto` (the modern entry point). Do NOT also
# wrap with `ddtrace-run`: both bootstrap ddtrace, and under uWSGI prefork the second
# attempt aborts Flask auto-instrumentation. Flask.wsgi_app still ends up looking
# wrapped, but emits no spans, so APM sees no flask.request and the service shows no
# web endpoints. `--lazy-apps` used to mask this by re-importing the app per worker;
# it was removed in IN-17316 to fix a 60s startup block, which exposed the bug.
#
# `--py-call-uwsgi-fork-hooks` lets ddtrace re-init the tracer in each forked worker.
# Do not re-add `--lazy-apps` here: with UWSGI_WORKERS defaulting to 250, each worker
# would re-import the app (that is what IN-17316 was fixing).
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 --import=ddtrace.auto --py-call-uwsgi-fork-hooks