#! /bin/bash --
set -x
export DOLLAR="$"

. "./startstop_utils.sh"

DJANGO_WEB_PID=none
DJANGO_QCLUSTER_PID=none
NGINX_PID=none
trap 'stop $DJANGO_WEB_PID $NGINX_PID $DJANGO_QCLUSTER_PID' SIGTERM SIGINT SIGQUIT SIGHUP ERR

# mkdir -p "$MEDIA_ROOT"
if [ -S '/django/sock' ]; then 
    # exit code speciale interpretato da briq-docker-watcher (in briq-docker-utils)
    # che forza la ricreazione del container
    exit 47
fi

echo >&2 "Nginx ..."
    envsubst <"/nginx.conf.tpl" >"/nginx.conf"
    { if [ "$NGINX_SSL" = "1" ]; then 
        { cat "${NGINX_SSL_CERTIFICATE}"; echo; cat "${NGINX_SSL_CHAIN}"; } > "/full_chain.pem";
        echo "listen ${EVERYTHING_LISTEN}:${EVERYTHING_PORT} ssl;
              ssl_certificate /full_chain.pem;
              ssl_certificate_key ${NGINX_SSL_KEY};
              ssl_session_cache shared:le_nginx_SSL:10m;
              ssl_session_timeout 1440m;
              ssl_session_tickets off;
              ssl_protocols TLSv1.2 TLSv1.3;
              ssl_prefer_server_ciphers off;
              ssl_ciphers \"ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384\";" 
        if [ -n "$NGINX_DH_PARAM" ]; then
            echo "ssl_dhparam ${NGINX_DH_PARAM};"
        fi
    else 
        echo "listen ${EVERYTHING_LISTEN}:${EVERYTHING_PORT};"
    fi; } > "/maybe_ssl.conf"
    nginx -c /nginx.conf -p / &
    NGINX_PID=$!

echo "Setting Django up..."
    cd /django/ || exit 1
    DJANGO_PROJ="$(poetry run python manage.py shell < get_django_proj.py)"
    if [[ "$(poetry run python manage.py help | grep -o '\[django_q\]')" == "[django_q]" ]]; then
      echo "Django qcluster..."
          poetry run python manage.py qcluster &
          DJANGO_QCLUSTER_PID=$!
    fi

    echo "Django web..."
        env DJANGO_SETTINGS_MODULE="$DJANGO_PROJ.settings" poetry run uvicorn "$DJANGO_PROJ".asgi:application --uds /django/sock --workers="${DJANGO_WORKERS:-4}" &
        DJANGO_WEB_PID=$!

wait