#!/usr/bin/env bash

if [ "$CONTAINER_DEPLOY" == "compose" ]; then
  echo "Waiting for postgres..."
  echo ${POSTGRES_HOST} ${POSTGRES_PORT}

  nc -z postgres 5432

  while ! nc -z postgres 5432; do
    sleep 0.1
  done

  echo "PostgreSQL started"
fi

if [ "${SERVICE}" == "web" ]; then
  echo "migrate database"
  python manage.py migrate
  echo "migration done"
  
  echo "run web server"
  gunicorn mysite.wsgi --timeout 10800 --worker-class=gevent -b 0.0.0.0:8000 -w 4 --limit-request-line=0
fi

if [ "${SERVICE}" == "worker" ]; then
  celery -A mysite worker --loglevel=error
fi

if [ "${SERVICE}" == "beat" ]; then
  rm celerybeat.pid -f
  celery -A mysite beat --schedule=./celery_schedule/celerybeat=schedule --loglevel=error
fi

exec "$@"
