#!/usr/bin/env bash
#
# This script is designed to be run inside the container
#

# fail hard and fast even on pipelines
set -eo pipefail

# set debug based on envvar
[[ $DEBUG ]] && set -x

echo system information:
echo "Django Version: $(./manage.py --version)"
python --version

# spawn confd in the background to update services based on changes
confd -backend env --confdir /app --log-level error --interval 5 &

mkdir -p /app/data/logs
chmod -R 777 /app/data/logs

# allow deis user group permission to Docker socket
if addgroup -g "$(stat -c "%g" /var/run/docker.sock)" docker; then
	addgroup deis docker
else
	addgroup deis "$(stat -c "%G" /var/run/docker.sock)"
fi

echo "Django checks:"
python /app/manage.py check --deploy api

echo "Health Checks:"
python /app/manage.py healthchecks

echo "Database Migrations:"
sudo -E -u deis python /app/manage.py migrate --noinput

# spawn a gunicorn server in the background
sudo -E -u deis gunicorn -c /app/deis/gconf.py deis.wsgi &

python /app/manage.py load_db_state_to_k8s

# smart shutdown on SIGTERM (SIGINT is handled by gunicorn)
function on_exit() {
	GUNICORN_PID=$(cat /tmp/gunicorn.pid)
	kill -TERM "$GUNICORN_PID" 2>/dev/null
	wait "$GUNICORN_PID" 2>/dev/null
	exit 0
}
trap on_exit TERM

echo deis-controller running...

wait
