#!/command/with-contenv bash

set -o errexit
set -o nounset
set -o pipefail
shopt -s inherit_errexit

ROMM_LOG_TAG="gunicorn"
# shellcheck source=SCRIPTDIR/../../scripts/lib.sh
source /etc/s6-overlay/scripts/lib.sh

record_process_group

# Wire LOGLEVEL into Gunicorn's logging config so it respects the env var.
gunicorn_level="${LOGLEVEL^^}"
gunicorn_log_config="/tmp/gunicorn/logging.conf"
# Copy the config to a writable runtime path so this works on read-only root filesystems.
mkdir -p /tmp/gunicorn
cp /etc/gunicorn/logging.conf "${gunicorn_log_config}"
sed -i '/\[logger_gunicorn\]/,/^\[/ s/^level=.*/level='"${gunicorn_level}"'/' "${gunicorn_log_config}"

info_log "Starting backend"

export PYTHONUNBUFFERED=1
export PYTHONDONTWRITEBYTECODE=1

cd /backend || error_log "/backend directory doesn't seem to exist"

declare -a wrap=()
otel_prefix wrap api

# WEB_SERVER_KEEPALIVE must outlive nginx's upstream idle timeout (60s), or the
# pooled connection is reaped before nginx can reuse it.
exec "${wrap[@]}" gunicorn \
	--bind=0.0.0.0:"${DEV_PORT:-5000}" \
	--no-control-socket \
	--forwarded-allow-ips="${FORWARDED_ALLOW_IPS:-127.0.0.1,::1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,100.64.0.0/10,fc00::/7}" \
	--worker-class uvicorn_worker.UvicornWorker \
	--workers "${WEB_SERVER_CONCURRENCY:-4}" \
	--timeout "${WEB_SERVER_TIMEOUT:-300}" \
	--keep-alive "${WEB_SERVER_KEEPALIVE:-65}" \
	--max-requests "${WEB_SERVER_MAX_REQUESTS:-1000}" \
	--max-requests-jitter "${WEB_SERVER_MAX_REQUESTS_JITTER:-100}" \
	--worker-connections "${WEB_SERVER_WORKER_CONNECTIONS:-1000}" \
	--error-logfile - \
	--log-config "${gunicorn_log_config}" \
	main:app
