#!/usr/bin/env bash
set -euo pipefail

cp mapping/zrn/web_viewer/backend/app.py .
pwd

# This allows us to set the env var in a live deployment to have a container
# come up that has no entrypoint failures which we can then attach to and debug
if [[ ! -v BACKEND_DUMMY_ENTRY_OVERRIDE ]]; then
    echo "no entry override provided, proceeding ..."
else
    echo "using dummy entry override"
    /bin/bash ; sleep infinity
fi

if [[ -z "${1:-}" || "$1" != "--local" ]]; then
    echo "Using multi worker and redis cache"

    export REDIS_HOST="${REDIS_HOST:-localhost}"
    export REDIS_PORT="${REDIS_PORT:-6379}"
    export PYTHONUNBUFFERED="${PYTHONUNBUFFERED:-0}"

    echo "REDIS_HOST $REDIS_HOST"
    echo "REDIS_PORT $REDIS_PORT"
    echo "PYTHONUNBUFFERED $PYTHONUNBUFFERED"

    python3.6 -m gunicorn.app.wsgiapp  \
    --bind 0.0.0.0:8081 'app:app' \
    --workers 20 \
    --log-level=debug \
    --worker-class=eventlet \
    --max-requests 20
    --max-requests-jitter 10
    --timeout 90
else
    echo "Using single process with Flask development server and in-process cache"
    export FLASK_APP=./mapping/zrn/web_viewer/backend/app
    python3.6 -m flask run -h 0.0.0.0 -p 8081
fi
