#!/usr/bin/env bash
# Shared Andrea web-service entrypoint. Optional tcmalloc preload (a RUNTIME toggle via
# $USE_TCMALLOC — LD_PRELOAD must be set before python starts, so it lives here in the shell, not
# in the gunicorn conf), then exec gunicorn with the shared bounded-worker config.
#
# A service copies this verbatim and sets two env vars (unit/compose/Dockerfile):
#   SVC_WSGI=myservice.wsgi:application     # the WSGI app to serve
#   SVC_BIND=0.0.0.0:8769                   # host:port to bind (consumed by gunicorn_conf)
# Everything else (workers/threads/timeout) is env-tunable via andrea_svc_web.gunicorn_conf.
set -e
: "${SVC_WSGI:?SVC_WSGI must be set (e.g. myservice.wsgi:application)}"

case "${USE_TCMALLOC:-0}" in
  1|true|yes|on|TRUE|YES|ON)
    TCM="$(ls /usr/lib/libtcmalloc_minimal.so.4 /usr/lib/*/libtcmalloc_minimal.so.4 \
              /opt/gperftools*/lib/libtcmalloc_minimal.so.4 2>/dev/null | head -1)"
    if [ -n "$TCM" ]; then
      export LD_PRELOAD="${TCM}${LD_PRELOAD:+:$LD_PRELOAD}"
      echo "[entrypoint] tcmalloc preloaded: $TCM"
    else
      echo "[entrypoint] USE_TCMALLOC set but libtcmalloc_minimal.so.4 not found — continuing without"
    fi
    ;;
  *)
    echo "[entrypoint] tcmalloc OFF (USE_TCMALLOC=${USE_TCMALLOC:-0})"
    ;;
esac

exec gunicorn -c python:andrea_svc_web.gunicorn_conf "$SVC_WSGI"
