#!/usr/bin/env node
/**
 * @overview Start the apeman app with node cluster server.
 * @see {@link http://nodejs.org/api/cluster.html | cluster}
 *
 */

process.env.NODE_ENV = '{{NODE_ENV}}';

var cluster = require('cluster'),
    port = require('../ports')['{{CONTEXT_NAME}}'],
    numberOfWorkers = require('os').cpus().length,
    newContext = require('../serverside/context').{{CONTEXT_LOADER_NAME}},
    newLogger = require('../serverside/logger').{{SERVER_LOGGER_CREATOR_MODULE_NAME}},
    newServer = require('../serverside/server').{{SERVER_CREATOR_MODULE_NAME}};

if (cluster.isMaster) {

    require('apeman').task('{{CONSTANTS_TASK_NAME}}', {debug: false}, function (){

        var context = newContext(),
            logger = newLogger(context);

        for (var i = 0; i < numberOfWorkers; i++) {
            cluster.fork();
        }

        logger.clusterStarting(numberOfWorkers);
        var listeningCount = 0;

        cluster.on('listening', function (worker, address) {
            logger.clusterWorkerStart(worker.process.pid);
            listeningCount++;
            var ready = listeningCount == numberOfWorkers;
            if (ready) {
                logger.serverStarted(port);
            }
        });

        cluster.on('disconnect', function (worker) {
            var pid = worker.process.pid;
            logger.clusterWorkerDied(pid);
            logger.clusterWorkerRestarting(pid);
            cluster.fork();
        });
    });

} else {

    var context = newContext(),
        logger = newLogger(context),
        server = newServer(context);

    server.listen(port);

    process.clusterDomainError = function (err) {
        logger.error(err);
        server.close();
        cluster.worker.disconnect();
    };
}

