#!/bin/bash
#
# Start celery for Django apps in
# several django environments.
# Install in /usr/local/sbin
#
WORKER_USER=${WORKER_USER:-iritic}
WORKER_GROUP=${WORKER_GROUP:-apache}
# Pid File directory
RUN_DIR=${RUN_DIR:-/var/run/django}
# The Base Directory where all
# Django Apps reside 
# here:
#{BASE_DIR}
#├── djangoappname
#│   ├── env         (virtualenv directory)
#│   ├── manage.py   (Django manage script)
#(...)
#
BASE_DIR=${BASE_DIR:-/var/www/wsgi}
# Option for celery worker
CELERY_OPTS=${CELERY_OPTS:-"--autoreload --autoscale=3,1 --beat"}
# Logs
LOG_DIR=${LOG_DIR:-/var/log/django}
LOG=${LOG_DIR}/${Me}_celery.log
# Django App name
Me=$1

if [[ "${USER}" = "root" ]]
then
    CLRY_OPTS="${CELELRY_OPTS} --uid=${WORKER_USER} --gid=${WORKER_GROUP}"
else
    CLRY_OPTS="${CELELRY_OPTS}"
fi
CLRY_OPTS="${CLRY_OPTS} --pidfile=${RUN_DIR}/${Me}.pid"
mkdir -p ${RUN_DIR}
chown ${WORKER_USER}:${WORKER_GROUP} ${RUN_DIR}
source ${BASE_DIR}/${Me}/env/bin/activate
cd ${BASE_DIR}/${Me}
${VIRTUAL_ENV}/bin/python manage.py celery worker ${CLRY_OPTS} \
    -n ${Me}@$(hostname) --logfile=${LOG} >> ${LOG} 2>&1  &
deactivate