#! /bin/bash --

cd "$(dirname "$0")" || exit 1
. "docker/test_and_build/startstop_utils.sh"

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

root="$(pwd)"
export root
source ".env"
# # DECOMMENTARE QUI DI SEGUITO SE NEL PROGETTO SERVE REDIS:
# if ! nc -z "$REDIS_HOST" "$REDIS_PORT"; then
#   echo >&2 "Non c'è redis su $REDIS_HOST:$REDIS_PORT"
#   exit 1
# fi
pushd django/ || exit 1
  echo >&2 "Starting django web server..."
    poetry run python manage.py runserver "127.0.0.1:$DJANGO_PORT" &
    DJANGO_WEB_PID=$!
#   echo >&2 "Starting django qcluster..."
#     poetry run python manage.py qcluster &
#     DJANGO_QCLUSTER_PID=$!
popd || exit 1
pushd vue || exit 1
  echo >&2 "Starting vue dev server..."
  npm run serve -- --port "$VUE_PORT" &
  VUE_PID=$!

popd || exit 1
echo >&2 "Starting nginx..."
  envsubst < nginx_localrun.conf.tpl > nginx_localrun.conf
  nginx -c "$root/nginx_localrun.conf"&
  NGINX_PID=$!

echo >&2 "Starting docker compose localrun services..."
  export COMPOSE_PROJECT_NAME="sangue_localrun"
  docker-compose --log-level error -f docker-compose-localrun.yml up --timeout 1 1>/dev/null
  # ctrl-c su docker compose killa tutto. docker-compose sostituisce il wait.