#!/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
[[ $DEIS_DEBUG == "true" ]] && set -x

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

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

# modify deis user groups to grant access to Docker socket
DOCKER_SOCKET_GID=$(stat -c "%g" /var/run/docker.sock)
DOCKER_SOCKET_GROUP=$(getent group "$DOCKER_SOCKET_GID" | cut -d : -f 1 || :)
if [[ -z "$DOCKER_SOCKET_GROUP" ]]; then
  DOCKER_SOCKET_GROUP=docker
  groupadd -g "$DOCKER_SOCKET_GID" "$DOCKER_SOCKET_GROUP"
fi
if [[ "$DOCKER_SOCKET_GROUP" != "deis" ]]; then
  usermod -a -G "$DOCKER_SOCKET_GROUP" deis
fi

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

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

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

# spawn a gunicorn server in the background
echo ""
echo "Starting up Gunicorn"
sudo -E -u deis gunicorn -c /app/deis/gunicorn/config.py api.wsgi &

echo ""
echo "Loading database information to Kubernetes in the background"
echo "Log of the run can be found in /app/data/logs/load_db_state_to_k8s.log"
# python -u avoids output buffering
nohup python -u /app/manage.py load_db_state_to_k8s > /app/data/logs/load_db_state_to_k8s.log &

# 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 ""
echo deis-controller running...

wait
