#!/bin/bash

##
# Reflects database models to the postgres database if this script is run for
# the first time and runs the app in a Gunicorn server, optimized for a 4-core
# system. (4 cores * 2 + 1)
#
# Gunicorn documentation: https://docs.gunicorn.org/en/latest/index.html
# Flask documentation, more options and information: https://flask.palletsprojects.com/en/2.0.x/patterns/appfactories/
##

# https://www.geeksforgeeks.org/bash-scripting-how-to-check-if-file-exists/

# Check if this script has already been run. If not, reflect database models
# and save that information for next time by creating an ``already_run.lock``
# file.
if [ ! -f already_run.lock ];
then
	FLASK_APP=measurer python -m flask reflect &&
	touch already_run.lock
fi

# https://stackoverflow.com/a/13864829
# Thanks to Lionel and BSMP!

# If unset, do ``INFO`` by default
if [[ -z "${LOGGING_LEVEL+set}" ]]; then
	export LOGGING_LEVEL="INFO";
fi

# Run the Gunicorn server in another
python -m gunicorn -w 9 -b :5009 measurer:"create_app()" &

# https://docs.docker.com/config/containers/multi-service_container/

wait -n

# Exit with status of process that exited first
exit $?
