'use strict'
!(function(require, directRequire) {
  function a(a) {
    const b = parseInt(a.count || process.env.WORKER_COUNT),
      e = 0 < b ? Math.min(b, d.cpus().length) : d.cpus().length
    let f = 'undefined' == typeof a.respawn || !!a.respawn
    const g =
        a.outputStream && 'function' == typeof a.outputStream.write
          ? a.outputStream.write
          : console.log,
      h = a.workers || []
    a.verbose &&
      g(
        'Master started on pid ' +
          process.pid +
          ', forking ' +
          e +
          ' processes of type ' +
          a.identifier
      )
    for (let b = 0, d = e; 0 <= d ? b < d : b > d; 0 <= d ? ++b : --b) {
      const b = c.fork({ workerIdentifier: a.identifier })
      'function' == typeof a.workerListener &&
        b.on('message', a.workerListener),
        h.push(b)
    }
    return (
      c.on('disconnect', b => {
        a.verbose && g(b.process.pid + ' disconnect')
        const c = h.indexOf(b)
        ;-1 < c && h.splice(c, 1), a.onDisconnect && a.onDisconnect(b)
      }),
      c.on('exit', (b, d, e) => {
        a.verbose &&
          g(
            b.process.pid +
              ' died with ' +
              (e || 'exit code ' + d) +
              (f ? ', restarting' : '')
          )
        const i = h.indexOf(b)
        if ((-1 < i && h.splice(i, 1), a.onDisconnect && a.onDisconnect(b), f))
          return (
            (b = c.fork()),
            'function' == typeof a.workerListener &&
              b.on('message', a.workerListener),
            h.push(b)
          )
      }),
      process.on('SIGTERM', () => {
        ;(f = !1),
          a.verbose &&
            g(
              'QUIT received, will exit once all workers have finished current requests'
            )
        const b = []
        for (let a = 0, c = h.length; a < c; a++) {
          const c = h[a]
          b.push(c.send('quit')),
            setTimeout(() => {
              try {
                c.kill('SIGTERM')
              } catch (a) {}
            }, 1e3)
        }
        return (
          setTimeout(() => {
            try {
              process.exit()
            } catch (a) {}
          }, 5e3),
          b
        )
      })
    )
  }
  function b(a, b) {
    const c = a(b)
    return c
      ? ('function' == typeof c.on &&
          c.on('close', () => {
            return process.exit()
          }),
        'function' == typeof c.close
          ? process.on('message', a => {
              return 'quit' === a ? c.close() : null
            })
          : null)
      : null
  }
  const c = require('cluster'),
    d = require('os')
  module.exports = (d = () => {}, e = {}) => {
    Date.now()
    return c.isMaster ? a(e) : b(d, c.worker)
  }
})(require('lazyload'), require)
