#!/bin/bash

set -e

if [[ -z "${SLURM_HOST}" ]]; then
    echo "No SLURM_HOST specified, aborting..."
    exit 1
fi

if [[ -z "${MYSQL_HOST}" || -z "${MYSQL_PASSWORD}" ]]; then
    echo "Missing mysql credentials, MYSQL_HOST & MYSQL_PASSWORD, aborting..."
    exit 1
fi

if [[ -z "${REDIS_HOST}" ]]; then
  echo "No REDIS_HOST specified, aborting..."
  exit 1
fi

if [[ -z "${REDIS_PREFIX}" ]]; then
  echo "No REDIS_PREFIX specified, aborting..."
  exit 1
fi

if [[ -z "${MYSQL_POOL_SIZE}" ]]; then
  echo "Warning: No MYSQL_POOL_SIZE specified"
fi

# Set host of Slurm controller in conf
sed -i "s/^SlurmctldHost=.*/SlurmctldHost=${SLURM_HOST}/" /usr/local/etc/slurm.conf
if [[ -n "${SLURM_BACKUP_HOST}" ]]; then
    sed -i "s/^#SlurmctldHost=.*/SlurmctldHost=${SLURM_BACKUP_HOST}/" /usr/local/etc/slurm.conf
fi


service munge start
# Do not start slurmd!

if [[ $1 == "daemon" ]]; then
  echo "Starting poll_and_set_loop.sh"
  exec ./poll_and_set_loop.sh
elif [[ "$@" ]]; then
  exec $@
else
  # Each process assumes single-threaded access.
  # uWSGI tries to (ab)use the Copy On Write semantics of the fork() call whenever possible.
  # By default it will fork after having loaded your applications to share as much of their memory as possible.
  # To prevent database connection memory shared across process
  # we use 'lazy-apps' which instruct uWSGI to load the applications after each worker's fork()
  exec uwsgi --http-socket 0.0.0.0:80 \
    --master \
    --need-app \
    --wsgi-file app.py \
    --callable app \
    --processes ${UWSGI_NUM_PROCESSES:-16} \
    --lazy-apps
fi
