#!/bin/bash
# We're going to continuously restart the server as long as
# it exited without error. This allows /shutdown to work without
# causing the container to go into crash restart loop, which makes
# testing more efficient. If the server crashes for some reason,
# we don't want it restarting indefinitely
#
# The following is potentially a bit of a hack; we're telling
# the container (Ubuntu) to load Python packages that in our
# dev / test environment are Darwin / OS X. If there are binaries
# anywhere in site-packages, that could create problems. This
# is attempting to avoid building the requirements.txt dependencies
# into the docker image, which would result in a new image each
# time we change a package version.
export PYTHONPATH=/app/lib/python3.7/site-packages
SERVER_EXIT=0
while [ "$SERVER_EXIT" -eq "0" ]; do
    # Set up local development environment variables
    source /app/bin/local-env
    # Set up application environment based on NODE_ENV value
    source /app/bin/app-env
    # The script bin/testme will write 'run_coverage' into 
    # coverage/runType.bash. Based on the value 'run_coverage', we'll
    # either invoke the server directly, or invoke it in the python
    # coverage tool
    source /app/coverage/runType.bash
    echo "Run coverage = $run_coverage"
    if [ "$run_coverage" -gt "0" ]; then
        echo "Launching coverage run of server"
        coverage run -a --source /app/src,/app/src/dm,/app/src/api,/app/src/util /app/src/server.py
        SERVER_EXIT=$?
        echo "Listing contents of /coverage"
        ls -al /app/coverage
        cd /app/coverage
        echo "About to run coverage report"
        coverage report -m --skip-covered > coverage.report
        # Need to set run coverage back to 0, so that when the server restarts,
        # it doesn't clear the coverage results
        echo "export run_coverage=0" > /app/coverage/runType.bash
    else
        echo "dev-server-loop: starting server with spec: ${OPENAPI_SPEC}"
        python3.7 /app/src/server.py
        SERVER_EXIT=$?
        echo "dev-server-loop: server exited with result: ${SERVER_EXIT}!"
    fi
done
