#!/bin/bash

set_is_prod_test_env_var=''

if [ -n "$IS_PROD_TEST" ]; then
  echo "IS_PROD_TEST: $IS_PROD_TEST"
  set_is_prod_test_env_var='-e IS_PROD_TEST=true'
fi


# Go to the project directory (whih is the parent directory).
script_dir=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
cd $script_dir
cd ..

# cli = comman line interface. That is, starts a prompt where you can type
# things like 'clean', 'test', 'compile', 'run', 'dist', 'console'.

# (Don't start nginx — apparently it won't find the app container, because the app
# container is here started with 'run' (not 'up') I would think, so it doesn't
# get the correct network address ? )

# Find amount-of-memory-to-use in docker-compose.yml:
if [ -z "$PLAY_HEAP_MEMORY_MB" ]; then
  PLAY_HEAP_MEMORY_MB=`grep 'PLAY_HEAP_MEMORY_MB:' docker-compose.yml | egrep -o '[0-9]+'`
fi

# Let's use at least this much memory — running tests needs a lot,
# but only 2800 by default in docker-compose.yml
if [ "$PLAY_HEAP_MEMORY_MB" -lt "5120" ]; then
  PLAY_HEAP_MEMORY_MB=5120
fi

# Set Java's user.home to /home/owner so sbt and Ivy will cache downloads there. [SBTHOME]
# Actually not needed in this case? because gets set in the entrypoint.sh. Do anyway, won't hurt.
# Pass PLAY_HEAP_MEMORY_MB to both Play Framework in the Docker container via the env var,
# and to SBT via --mem.
sudo PLAY_HEAP_MEMORY_MB=$PLAY_HEAP_MEMORY_MB \
  docker-compose run --rm --service-ports $set_is_prod_test_env_var app \
  /opt/sbt/bin/sbt \
  --mem $PLAY_HEAP_MEMORY_MB \
  -J-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:9999 \
  -J-Xss30m \
  -Duser.home=/home/owner \
  -Dcom.sun.management.jmxremote.port=3333 \
  -Dcom.sun.management.jmxremote.ssl=false \
  -Dcom.sun.management.jmxremote.authenticate=false \
  -Dhttp.port=9000 \
  -Dhttps.port=9443 \
  `# SSL has security flaws. Use TLS instead. [NOSSL] [PROTOCONF]` \
  -Ddeployment.security.SSLv2Hello=false \
  -Ddeployment.security.SSLv3=false \
  -Dhttps.protocols=TLSv1.1,TLSv1.2 \
  -Djdk.tls.client.protocols=TLSv1.1,TLSv1.2 \
  `# Otherwise ignored (really!?), although as per the docs it should be found since it's on the classpath.` \
  -Dlogback.configurationFile=/opt/talkyard/app/conf/logback.xml \
  `# log4j2 problem, disable this:` \
  -Dlog4j2.formatMsgNoLookups=true \
  -Dconfig.file=/opt/talkyard/app/conf/app-dev.conf \
  "$@"

# -J-XX:+HeapDumpOnOutOfMemoryError \
# -J-XX:HeapDumpPath=/opt/talkyard/app/ \
