'use strict';
var log = require('./log');
module.exports = function (workers, options) {
  var DEBUG = options.debug;
  var CONCURRENCY = options.concurrency;
  var PORT = options.port;
  var serverInstance;
  var serverIsRunning;

  function serverCreate () {
    var hash = require('string-hash');
    return require('net')
      .createServer({ pauseOnConnect: true }, function (connection) {
        var index = hash(connection.remoteAddress) % CONCURRENCY;
        workers.entrust(index, connection);
      });
  }

  function serverStart (callback) {
    serverIsRunning = true;
    serverInstance = serverCreate();
    serverInstance.listen(PORT, callback);
  }

  function serverStop (callback) {
    if (serverIsRunning) {
      serverIsRunning = false;
      serverInstance.close(function (err) {
        if (err) console.log(err);
        else return callback();
      });
    }
  }

  function stop () {

    // stop proxy server
    if (DEBUG) log('MASTER  stop..');
    serverStop(function () {
      if (DEBUG) log('MASTER  ..stopped');

      // stop nodes
      if (DEBUG) log('WORKERS  stop..');
      workers.stop();
    });
  }

  function start () {
    
    // start proxy server
    if (DEBUG) log('MASTER  start..');
    serverStart(function () {
      if (DEBUG) log('MASTER  ..started at port %d', PORT);

      // start nodes
      if (DEBUG) log('WORKERS  start..');
      workers.start();

      // stop everything when requested
      process
        .on('SIGINT', stop)
        .on('SIGTERM', stop);
    });
  }

  return {
    start: start,
    stop: stop
  };
};

@@ -204,31 +204,8 @@
 nce;
-%0A  var serverIsRunning;
 %0A%0A  
@@ -531,36 +531,8 @@
 ) %7B%0A
-    serverIsRunning = true;%0A
     
@@ -651,68 +651,8 @@
 ) %7B%0A
-    if (serverIsRunning) %7B%0A      serverIsRunning = false;%0A  
     
@@ -691,26 +691,24 @@
 rr) %7B%0A      
-  
 if (err) con
@@ -728,18 +728,16 @@
 ;%0A      
- 
- 
 else ret
@@ -760,20 +760,12 @@
     
-  
 %7D);%0A
-    %7D%0A
   %7D%0A

disable master running check before stop