#!/usr/bin/env php
<?php

// Find and initialize Composer
$files = [
    __DIR__ . '/../../vendor/autoload.php',
    __DIR__ . '/../../../autoload.php',
    __DIR__ . '/../../../../autoload.php',
    __DIR__ . '/../vendor/autoload.php',
];

foreach ($files as $file) {
    if (file_exists($file)) {
        require_once $file;
        break;
    }
}

if (!class_exists('Composer\Autoload\ClassLoader', false)) {
    die(
        'You need to set up the project dependencies using the following commands:' . PHP_EOL .
        'curl -s http://getcomposer.org/installer | php' . PHP_EOL .
        'php composer.phar install' . PHP_EOL
    );
}

// Set which queues to monitor '*'
$QUEUE = getenv('QUEUE');
if (empty($QUEUE)) {
    die("Set QUEUE env var containing the list of queues to work.\n");
}

/**
 * REDIS_BACKEND can have simple 'host:port' format or use a DSN-style format like this:
 * - redis://user:pass@host:port
 *
 * Note: the 'user' part of the DSN URI is required but is not used.
 */
$REDIS_BACKEND = getenv('REDIS_BACKEND');

/**
 * REDIS_BACKEND_DB overrides default Redis DB
 */
$REDIS_BACKEND_DB = getenv('REDIS_BACKEND_DB');
if (!empty($REDIS_BACKEND)) {
    if (empty($REDIS_BACKEND_DB)) {
        \Resque\Resque::setBackend($REDIS_BACKEND);
    } else {
        \Resque\Resque::setBackend($REDIS_BACKEND, $REDIS_BACKEND_DB);
    }
}

// Set Logging level
$logLevel = false;
$LOGGING = getenv('LOGLEVEL');
if (!empty($LOGGING)) {
    $logLevel = $LOGGING;
}

// Bootstrap file
$APP_INCLUDE = getenv('APP_INCLUDE');
if ($APP_INCLUDE) {
    if (!file_exists($APP_INCLUDE)) {
        die('APP_INCLUDE (' . $APP_INCLUDE . ") does not exist.\n");
    }

    require_once $APP_INCLUDE;
}

// See if the APP_INCLUDE containes a logger object,
// If none exists, fallback to internal logger
if (!isset($logger) || !is_object($logger)) {
    $logger = new \Resque\Log($logLevel);
}

// Determines if blocking or not
$BLOCKING = getenv('BLOCKING') !== FALSE;

// Interval to check for jobs
$interval = 5;
$INTERVAL = getenv('INTERVAL');
if (!empty($INTERVAL)) {
    $interval = $INTERVAL;
}

// Sets worker count
$count = 1;
$COUNT = getenv('COUNT');
if (!empty($COUNT) && $COUNT > 1) {
    $count = $COUNT;
}

// Determines redis key prefix
$PREFIX = getenv('PREFIX');
if (!empty($PREFIX)) {
    $logger->log(\Psr\Log\LogLevel::INFO, 'Prefix set to {prefix}', ['prefix' => $PREFIX]);
    \Resque\Redis::prefix($PREFIX);
}

if ($count > 1) {
    for ($i = 0; $i < $count; ++$i) {
        $pid = \Resque\Resque::fork();
        if ($pid === false || $pid === -1) {
            $logger->log(\Psr\Log\LogLevel::EMERGENCY, 'Could not fork worker {count}', ['count' => $i]);
            die();
        } elseif (!$pid) {
            // Child, start the worker
            $queues = explode(',', $QUEUE);
            $worker = new \Resque\Worker($queues);
            $worker->setLogger($logger);
            $logger->log(\Psr\Log\LogLevel::NOTICE, 'Starting worker {worker}', ['worker' => $worker]);
            $worker->work($interval, $BLOCKING);
            break;
        }
    }
} else {
    // Start a single worker
    $queues = explode(',', $QUEUE);
    $worker = new \Resque\Worker($queues);
    $worker->setLogger($logger);

    $PIDFILE = getenv('PIDFILE');
    if ($PIDFILE) {
        file_put_contents($PIDFILE, getmypid()) or
        die('Could not write PID information to ' . $PIDFILE);
    }

    $logger->log(\Psr\Log\LogLevel::NOTICE, 'Starting worker {worker}', ['worker' => $worker]);
    $worker->work($interval, $BLOCKING);
}
