#!/bin/bash

set -e

ARGS=$@
PROG=$(basename $0)

# Use supervisord or not (default to not)
USE_SUPERVISOR=

# Workers using more than MAXMEM will be restarted
MAXMEM=204800

# Number of workers to run in parrallel
CONCURRENCY=1

# Debug level of celery output
LEVEL=info

usage() {
    cat << EOF
USAGE: $0 [--concurrency N] [--maxmem M] [--level L] [--keep-alive]

Start celery with the given number of workers. If --keep-alive is specified,
start celery by way of supervisord, after generating a supervisor configuration
file to monitor and start the celery workers.

OPTIONS:
  --keep-alive      Use supervisord to keep Celery alive
  --concurrency N   Number of Celery workers to execute in parrallel (default: $CONCURRENCY)
  --maxmem M        Workers using more than M megabytes get restarted (default: $MAXMEM)
  --level L         Debug level of Celery workers (default: $LEVEL)
  --help            This help

USAGE:
  # Start celery with 8 workers and debug level
  pymasync --concurrency 8 --level debug

EOF
}


parse_args() {
    while [ "$1" != "" ]; do
        case $1 in
            "--keep-alive")   USE_SUPERVISOR=1;;
            "--debug")        set -x;;
            "--concurrency")  shift; CONCURRENCY=$1;;
            "--maxmem")       shift; MAXMEM=$1;;
            "--level")        shift; LEVEL=$1;;
            "-h" | "--help")  usage; exit 0;;
            *)                usage; exit 0;;
        esac
        shift
    done
}

parse_args $ARGS

PATH_CELERY=$(which celery)
CMD="$PATH_CELERY worker -E -A pymacaron_async --concurrency=$CONCURRENCY --loglevel=$LEVEL --include pymacaron_async.loader --max-memory-per-child=$MAXMEM"

if [ -z "$USE_SUPERVISOR" ]; then
    eval $CMD
fi

cat <<EOF > supervisord.conf
# Auto-generated by pymasync - DONT TOUCH!
[supervisord]
loglevel=$LEVEL
nodaemon=false

[supervisorctl]
serverurl=unix:///tmp/supervisor.sock

[program:celeryd]
command=$CMD
autostart=true
autorestart=true
startsecs=10
stopwaitsecs=600

EOF

echo "=> Command to start Celery:"
cat supervisord.conf | grep command | sed -e "s/command=//"

echo "=> Starting supervisord & celery"
supervisord
