#!/usr/bin/env sh

if [ $(uname -s) = "Darwin" ]; then
  ulimit -n 2048  # increase file descriptor limits on OS X
fi

if [ -n "$HTTPOBS_MAX_CONCURRENCY" ]; then
  CONCURRENCY=$HTTPOBS_MAX_CONCURRENCY
  LOGLEVEL=warning
elif [ -n "$HTTPOBS_DEV" ]; then
  CONCURRENCY=48
  LOGLEVEL=info
else
  CONCURRENCY=96
  LOGLEVEL=warning
fi

# Kill the existing celery workers
PID='/var/run/httpobs/scanner.pid'
if [ -f $PID ];
then
    kill `cat $PID`
    rm -f $PID
fi

# Execute celery
celery \
  -A httpobs.scanner.tasks \
  --autoscale=$CONCURRENCY,4 \
  --broker=$HTTPOBS_BROKER_URL \
  --detach \
  --hostname='scanner@%h' \
  --logfile='/var/log/httpobs/scanner.log' \
  --loglevel=$LOGLEVEL \
  --maxtasksperchild=16 \
  --pidfile='/var/run/httpobs/scanner.pid' \
worker

# Run the scanner
python3 -u httpobs/scanner/main.py >> /var/log/httpobs/scan-worker.log 2>&1
